[POJ1655]Balancing Act
Posted 小飞淙的云端
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[POJ1655]Balancing Act相关的知识,希望对你有一定的参考价值。
题目描述 Description |
Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to be the size of the largest tree in the forest T created by deleting that node from T. Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two. |
输入描述 Input Description |
The first line of input contains a single integer t (1 <= t <= 20), the number of test cases. The first line of each test case contains an integer N (1 <= N <= 20,000), the number of congruence. The next N-1 lines each contains two space-separated node numbers that are the endpoints of an edge in the tree. No edge will be listed twice, and all edges will be listed.
|
输出描述 Output Description |
For each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node. |
样例输入 Sample Input |
1 |
样例输出 Sample Output |
1 2 |
数据范围及提示 Data Size & Hint |
之前的一些废话:会考结束,没出成绩,准备期末复习。做这种题就是在浪费生命,不如怒刷龙珠。
题解:求树的重心。
代码:
#include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<queue> #include<cstdio> using namespace std; typedef long long LL; #define mem(a,b) memset(a,b,sizeof(a)) typedef pair<int,int> PII; inline int read() { int x=0,f=1;char c=getchar(); while(!isdigit(c)){if(c==\'-\')f=-1;c=getchar();} while(isdigit(c)){x=x*10+c-\'0\';c=getchar();} return x*f; } const int maxn=20010; struct Edge { int u,v,next; Edge() {} Edge(int _1,int _2,int _3):u(_1),v(_2),next(_3) {} }e[maxn<<1]; int T,n,ce,a,b,first[maxn],size[maxn],A[maxn],ms[maxn],ans; void addEdge(int a,int b) { e[++ce]=Edge(a,b,first[a]);first[a]=ce; e[++ce]=Edge(b,a,first[b]);first[b]=ce; } void dfs(int now,int fa) { size[now]=1; for(int i=first[now];i!=-1;i=e[i].next) if(e[i].v!=fa) { dfs(e[i].v,now); size[now]+=size[e[i].v]; if(size[e[i].v]>size[ms[now]])ms[now]=e[i].v; } A[now]=max(size[ms[now]],n-size[now]); ans=min(ans,A[now]); } int main() { T=read(); while(T--) { mem(first,-1);mem(e,0);mem(A,0);mem(size,0);mem(ms,0);ans=maxn;ce=-1; n=read(); for(int i=1;i<n;i++)a=read(),b=read(),addEdge(a,b); dfs(1,0); for(int i=1;i<=n;i++)if(A[i]==ans) { printf("%d %d\\n",i,ans); break; } } }
总结:
以上是关于[POJ1655]Balancing Act的主要内容,如果未能解决你的问题,请参考以下文章