Balancing Act
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7434 | Accepted: 3007 |
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.
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.
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.
Input
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
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 7 2 6 1 2 1 4 4 5 3 7 3 1
Sample Output
1 2
Source
Memory: 1480 KB
Time: 141 MS
Language: C++
Result:
Accepted
说实话这和前面的那个3140都是由一个代码改的,这几个题真是太像了。这个题是让你求哪个点的ballance最小以及它的ballance是多少
#include<iostream>
#include<vector>
using namespace std;
struct tree{
int val,nod;//去掉改点后子节点中包含节点最大的数目和包含节点数
vector<int>son;//子节点id
}f[20005];
int vis[20005],n,m;
void dfs(int x)
{
int i,j;
f[x].nod=1;//含本身
f[x].val=0;
vis[x]=1;
for(i=0;i<f[x].son.size();i++)
{
if(!vis[f[x].son[i]])
{
dfs(f[x].son[i]);
f[x].nod+=f[f[x].son[i]].nod;//记录子树及其本身节点数目。f[f[x].son[i]]才是变量
if(f[x].val<f[f[x].son[i]].nod)
f[x].val=f[f[x].son[i]].nod;
}
}
if(f[x].val<n-f[x].nod)
f[x].val=n-f[x].nod;//确定是不是除自己之外最大结点数
if(m>f[x].val)
m=f[x].val;//这个就是求最小ballance的
}
int main()
{
int i,j,k,a,b,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(vis,0,sizeof(vis));
m=1000000;
for(i=1;i<=n;i++)
f[i].son.clear();
for(i=0;i<n-1;i++)
{
scanf("%d%d",&a,&b);
f[b].son.push_back(a);//双向的
f[a].son.push_back(b);
}
dfs(1);//输入的是从1开始的所以从1开始搜索
for(i=1;i<=n;i++)//也是从1开始
{
if(f[i].val==m)
{
printf("%d %d\n",i,f[i].val);
break;
}
}
}
return 0;
}