树的重心模板
树的重心模板
标签(空格分隔): 模板
POJ - 3107
数的重心裸题
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
typedef pair<int, int> Pii;
const int MAXN = 5e4 + 50;
int size[MAXN], f[MAXN], n, ans = 0x4f4f4f4f, cnt = 0;
int head[MAXN];
Pii e[MAXN << 1];
inline int read()
{
int res = 0;
char ch = getchar();
while(48 > ch || ch > 57)
ch = getchar();
while(48 <= ch && ch <= 57){
res = (res << 3) + (res << 1) + ch - 48;
ch = getchar();
}
return res;
}
void add_edge(int u, int v)
{
e[cnt].first = v;
e[cnt].second = head[u];
head[u] = cnt;
cnt ++;
e[cnt].first = u;
e[cnt].second = head[v];
head[v] = cnt;
cnt ++;
return;
}
void dfs(int now, int fa)
{
size[now] = 1;
int _max = -1;
for(int i = head[now]; i != -1; i = e[i].second){
int v = e[i].first;
if(v == fa) continue;
dfs(v, now);
size[now] += size[v];
_max = max(_max, size[v]);
}
f[now] = max(_max, n - size[now]);
ans = min(ans, f[now]);
return;
}
int main()
{
n = read();
for(int i = 0; i <= n; i ++)
head[i] = -1;
for(int i = 0; i < n - 1; i ++){
add_edge(read(), read());
}
dfs(1, 0);
// cout << ans;
for(int i = 1; i <= n; i ++)
if(ans == f[i])
printf("%d ", i);
return 0;
}
胜负师是求道者与苦行僧的结合。