您的位置:首页 > 其它

SGU 134 Centroid【树的重心】

2013-08-14 11:01 239 查看
树的重心。递归求解即可。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
#define N 16100
vector<int> g
;
int n, cur, s
, f
;
void getroot(int now, int fa) {
s[now] = 1;
f[now] = 0;
int u;
for (int i=0; i<g[now].size(); i++)
if ((u = g[now][i]) != fa) {
getroot(u, now);
s[now] += s[u];
f[now] = max(f[now], s[u]);
}
f[now] = max(f[now], n-s[now]);
if (f[now] < f[cur]) cur = now;
}
int main() {
int a, b;
scanf("%d", &n);
for (int i=1; i<n; i++) {
scanf("%d%d", &a, &b);
g[a].push_back(b); g[b].push_back(a);
}
f[cur] = n;
getroot(1, cur=0);
vector<int> ans;
for (int i=1; i<=n; i++) if (f[i] == f[cur]) ans.push_back(i);
sort(ans.begin(), ans.end());
printf("%d %d\n", f[cur], ans.size());
printf("%d", ans[0]);
for (int i=1; i<ans.size(); i++) printf(" %d", ans[i]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: