首页 > 代码库 > POJ1655 Balancing Act

POJ1655 Balancing Act

题解:

树形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=20000+10;const int mod=1e9+7;int son[maxn],vis[maxn];int head[maxn];int n,Siz,cnt,ans;struct Edge{    int to,nxt;};Edge edge[2*maxn];void Init(){    cnt=0;    Siz=INF;    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){    vis[u]=1;    son[u]=0;    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||(tmp==Siz&&u<ans)){        Siz=tmp;        ans=u;    }}int main(){    int t,u,v;    scanf("%d",&t);    while(t--){        Init();        scanf("%d",&n);        for(int i=1;i<=n-1;i++){            scanf("%d%d",&u,&v);            addedge(u,v);addedge(v,u);        }        dfs(1);        printf("%d %d\n",ans,Siz);    }    return 0;}

 

POJ1655 Balancing Act