标签:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10347 | Accepted: 4285 |
Description
Input
Output
Sample Input
1
7
2 6
1 2
1 4
4 5
3 7
3 1
Sample Output
1 2
Source
1 #include<cstdio> 2 #include<algorithm> 3 #include<cstring> 4 5 using namespace std; 6 7 const int maxn=20000+5; 8 const int inf=0x3f3f3f3f; 9 10 struct Edge 11 { 12 int to,next; 13 }edge[maxn<<1]; 14 15 int head[maxn]; 16 int tot; 17 int son[maxn]; 18 int siz[maxn]; 19 int ans[maxn]; 20 21 void init() 22 { 23 memset(head,-1,sizeof(head)); 24 tot=1; 25 memset(ans,0,sizeof(ans)); 26 memset(son,-1,sizeof(son)); 27 } 28 29 void addedge(int u,int v) 30 { 31 edge[tot].to=v; 32 edge[tot].next=head[u]; 33 head[u]=tot++; 34 } 35 36 void dfs(int u,int fa) 37 { 38 siz[u]=1; 39 for(int i=head[u];~i;i=edge[i].next) 40 { 41 int v=edge[i].to; 42 if(v==fa) 43 continue; 44 dfs(v,u); 45 siz[u]+=siz[v]; 46 if(son[u]==-1||siz[v]>siz[son[u]]) 47 son[u]=v; 48 } 49 } 50 51 int solve(int n) 52 { 53 dfs(1,-1); 54 55 for(int i=1;i<=n;i++) 56 ans[i]=max(siz[son[i]],n-siz[i]); 57 int id=1; 58 for(int i=2;i<=n;i++) 59 { 60 if(ans[i]<ans[id]) 61 id=i; 62 } 63 return id; 64 } 65 66 int main() 67 { 68 int test; 69 scanf("%d",&test); 70 while(test--) 71 { 72 int n; 73 scanf("%d",&n); 74 init(); 75 76 for(int i=1;i<n;i++) 77 { 78 int u,v; 79 scanf("%d%d",&u,&v); 80 addedge(u,v); 81 addedge(v,u); 82 } 83 84 int id=solve(n); 85 86 printf("%d %d\n",id,ans[id]); 87 } 88 89 return 0; 90 }
POJ 1655 Balancing Act 树的重心 基础题
标签:
原文地址:http://www.cnblogs.com/-maybe/p/4590674.html