首页 > 代码库 > codeforces 700B Connecting Universities

codeforces 700B Connecting Universities

蛮有意思的。。。。考虑每条边的贡献。

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#define maxv 200500#define maxe 400500using namespace std;int n,k,x,y,nume=0,g[maxv],size[maxv],fath[maxv];long long ans=0;bool vis[maxv];struct edge{    int v,nxt;}e[maxe];void addedge(int u,int v){    e[++nume].v=v;    e[nume].nxt=g[u];    g[u]=nume;}void dfs1(int x){    size[x]=0;    for (int i=g[x];i;i=e[i].nxt)    {        int v=e[i].v;        if (v!=fath[x])        {            fath[v]=x;            dfs1(v);            size[x]+=size[v];        }    }    if (vis[x]) size[x]++;}void dfs2(int x){    for (int i=g[x];i;i=e[i].nxt)    {        int v=e[i].v;        if (v!=fath[x])        {            ans+=min(size[v],2*k-size[v]);            dfs2(v);        }    }}int main(){    scanf("%d%d",&n,&k);    for (int i=1;i<=2*k;i++) {scanf("%d",&x);vis[x]=true;}    for (int i=1;i<=n-1;i++)    {        scanf("%d%d",&x,&y);        addedge(x,y);addedge(y,x);    }    dfs1(1);    dfs2(1);    printf("%I64d\n",ans);    return 0;}

 

codeforces 700B Connecting Universities