Balancing ActTime Limit: 1000MS Memory Limit: 65536KTotal Submissions: 14930 Accepted: 6341DescriptionConsider 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. For example, consider the tree: 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. For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number. InputThe 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.OutputFor each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node.Sample Input172 61 21 44 53 73 1Sample Output1 2SourcePOJ Monthly--2004.05.15 IOI 2003 sample task
树的重心。
思路就是找最大的子树的最小值。 一直没过的原因是.. 原来是先找到根,再从根开始访问,本以为这样不用vis标记 后来看数据发现这货根好像不是传统意义上的一个根 (怪不得)所以把它当无向图,加边加两次,加上vis。
#include#include #define MAXN 20005using namespace std;int cnt;int t,n,root;bool book[MAXN],vis[MAXN];int head[MAXN];int son[MAXN];int ans=1<<30,ansid;struct point{ int to,next;}e[2*MAXN];inline void add(int x,int y){ e[++cnt].to = y; e[cnt].next = head[x]; head[x]=cnt;}void dfs(int id){ vis[id]=1; int i,tmp=0; son[id]=1; for(i=head[id];i!=-1;i=e[i].next ){ int v=e[i].to ; if(vis[v]) continue;// vis[v]=1; dfs(v); son[id]+=son[v]; tmp=max(son[v],tmp); } //tmp is the max number of sub trees tmp=max(tmp,n-son[id]);// tmp=max(tmp,n-son[id]+1); if(tmp id)){ ans=tmp; ansid=id; }}int main(){ cin>>t; int x,y; int i; while(t--){ cnt=0;//!! memset(book,0,sizeof(book)); memset(head,-1,sizeof(head)); memset(son,0,sizeof(son));//!!! memset(vis,0,sizeof(vis));//!!! ans=1<<30; ansid=0; cin>>n; for(i=1;i >x>>y; add(x,y); add(y,x); book[y]=1; } i=1;// while(book[i]) i++;// root=i;// cout< <