首页 > 代码库 > POJ3107 Godfather

POJ3107 Godfather

题解:

树形dp求重心裸题

代码:

#include<bits/stdc++.h>using namespace std;#define pb push_back#define mp make_pair#define se second#define fs first#define ll long long#define CLR(x) memset(x,0,sizeof x)#define MC(x,y) memcpy(x,y,sizeof(x))  #define SZ(x) ((int)(x).size())#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)#define lson l,m,rt<<1#define rson m+1,r,rt<<1|1 #define INF 2097152typedef pair<int,int> P;const double eps=1e-9;const int maxn=50000+10;const int mod=1e9+7;int son[maxn],vis[maxn];int head[maxn];int n,Siz,cnt;struct Edge{    int to,nxt;};Edge edge[maxn*2];vector<int> vec;void Init(){    cnt=0;    Siz=INF;    vec.clear();    memset(vis,0,sizeof(vis));    memset(head,-1,sizeof(head));}void addedge(int u,int v){    edge[cnt].to=v;    edge[cnt].nxt=head[u];    head[u]=cnt++;}void dfs(int u){    son[u]=0;    vis[u]=1;    int tmp=0;    for(int i=head[u];~i;i=edge[i].nxt){        int v=edge[i].to;        if(!vis[v]){            dfs(v);            son[u]+=(son[v]+1);            tmp=max(tmp,son[v]+1);        }    }    tmp=max(tmp,n-son[u]-1);    if(tmp==Siz) vec.pb(u);    if(tmp<Siz){        vec.clear();        vec.pb(u);        Siz=tmp;    }}int main(){    int u,v;    while(~scanf("%d",&n)){        Init();        for(int i=1;i<=n-1;i++){            scanf("%d%d",&u,&v);            addedge(u,v);addedge(v,u);        }        dfs(1);        sort(vec.begin(),vec.end());        for(int i=0;i<vec.size()-1;i++) printf("%d ",vec[i]);        printf("%d\n",vec[vec.size()-1]);    }    return 0;}

 

POJ3107 Godfather