题意:求树的结点种去掉点后形成的森林的结点的最大值中的最小值。
思路:讲道理,我感觉这是模拟.....和昨天那道题很像。因为去掉结点,自己的子树肯定是分开的,所以对于u而言,它的balance就是max(sum[v],n-sum[u]); v是u的各个子树的结点数量。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 2e4 + 50;
const int inf = 0x3f3f3f3f;
struct node
{
int to,next;
node(){}
node(int a,int b){to = a; next = b;}
}edge[maxn << 1];
int h[maxn],sum[maxn];
int edgenum;int n;int ansmax = inf,ansi = 0;
void init()
{
for(int i = 0; i <= n; i++)
h[i] = -1, sum[i] = 0;
edgenum = ansi = 0, ansmax = inf;
}
void add(int f,int t)
{
edge[edgenum] = node(t,h[f]);
h[f] = edgenum++;
}
void solve(int u,int pre)
{
int temp = 0;
for(int i = h[u]; ~i; i = edge[i].next)
{
int v = edge[i].to;
if(v == pre) continue;
solve(v,u);
temp = max(temp,sum[v]);
sum[u] += sum[v];
}
sum[u] += 1;
temp = max(n-sum[u],temp);
if(ansmax > temp){ansmax = temp; ansi = u;}
else if(ansmax == temp)
{
if(u < ansi) ansi = u;
}
return ;
}
int main()
{
int t,a,b;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
init();
for(int i = 0; i < n-1 ; i++)
{
scanf("%d%d",&a,&b);
add(b,a); add(a,b);
}
solve(1,-1);
printf("%d %d\n",ansi,ansmax);
}
return 0;
}