题意:一个树上删掉一个点,使得得到的森林中的最大数的size作为结果,最小化这个结果。即求树的重心。
思路:删掉当前节点,得到的最大的树的大小就是dfs序中它所有的儿子的大小和他父树中的大小的最大值。 一遍dfs即可得到sz[]
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<algorithm>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<cstdlib>
#include<list>
#include<stack>
#include<cmath>
#include<iomanip>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
void debug() {cout << "ok running!" << endl;}
int n;
vector<int> mp[200005];
int sz[200005];
int ans, pos;
void dfs(int u, int v)
{
sz[u] = 1;
int res = 0;
for(int i = 0; i < mp[u].size(); ++i)
{
int to = mp[u][i];
if(to == v) continue;
//cout << u << " " << v << " " << to << endl;
dfs(to, u);
sz[u] += sz[to];
res = max(res, sz[to]);
}
res = max(res, n - sz[u]);
if(res < ans || res == ans && u < pos)
ans = res, pos = u;
}
int main()
{
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
#endif // ONLINE_JUDGE
int t;
cin >> t;
while(t--)
{
cin >> n;
for(int i = 0; i <= n; ++i) mp[i].clear();
for(int i = 0; i < n-1; ++i)
{
int x, y;
cin >> x >> y;
mp[x].push_back(y);
mp[y].push_back(x);
}
ans = 0x3f3f3f3f;
dfs(1, -1);
cout << pos << " " << ans << endl;
}
return 0;
}