思路:找平衡点,删掉一个点后子树节点差最小的就是平衡点,size[i]表示以i节点给根的子节点的个数,f[i]表示删除i节点后最大联通块的节点数,v代表i的子节点,f[i]=max(max(size[v]),n-size[i]),当i节点作为平衡点删去后,留下的最大联通块的节点数要么是他上面的树的节点(n-size[i])要么是子树的最大值size[v],然后在这里面求最小的就是要平衡点,再找一下这些平衡点的编号最小的。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=998244353;
const int N=2e6+10;
const int M=2e3+10;
const int inf=0x7f7f7f7f;
const int maxx=2e5+7;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1) res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
vector<int> G[2005];
int siz[1005];
int dp[1005];
int n;
int ans,id;
void dfs(int u,int fa)
{
siz[u]=1;
int res=0;
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(v==fa)continue;
dfs(v,u);
siz[u]+=siz[v];
res=max(res,siz[v]);
}
res=max(n-siz[u],res);
if(ans>res)
{
ans=res;id=u;
}
else if(ans==res)
{
id=min(id,u);
}
}
int main()
{
// int n;
cin>>n;
for(int i=0;i<n-1;i++)
{
int u,v;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
ans=id=1005;
dfs(1,-1);
cout<<id<<' '<<ans;
return 0;
}

京公网安备 11010502036488号