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;
}
#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;
}
相关文章推荐
- SGU 134 Centroid(树的重心)
- SGU 134. Centroid(树的重心)
- SGU 134 Centroid (树的重心)
- SGU 134 Centroid 找树的重心 水题
- sgu 134 Centroid 树的重心
- sgu 134 Centroid
- SGU 134 Centroid (树形dp 求树的中心)
- SGU 134.Centroid(图心)
- 树形DP求树的重心 --SGU 134
- Centroid - SGU 134(树的搜索)
- SGU134 Centroid
- 树形DP求树的重心 --SGU 134
- SGU 134 Centroid
- SGU 134 Centroid(树形dp)
- SGU134 Centroid
- SGU 134(树的重心)
- SGU 134 Centroid(树形DP)
- SGU 134.Centroid( 树形dp )
- SGU 134 树的重心
- SGU 134 Centroid