1021 Deepest Root (25分)
分析
在深度优先遍历的同时,计算连通分量的个数,以及最大深度的节点,加入set中。
第二次选第一次遍历得到的节点中的其中一个,开始深度优先遍历,得到的深度最深的节点也加入set中,从而得到所有的可以作为高度最大的树的根节点的节点。
提供一个测试用例
5
1 2
2 3
2 4
4 5
代码
#include<iostream>
#include<vector>
#include<set>
using namespace std;
int n, a, b, maxdepth = 1, marked[10010], components = 0;
vector<int> tree[10010];
set<int> s, ss;
void dfs(int k, int depth) {
marked[k] = 1;
if (depth > maxdepth) {
maxdepth = depth;
s.clear();
}
if (depth == maxdepth)s.insert(k);
for (int i = 0; i < tree[k].size(); ++i)
if (!marked[tree[k][i]])
dfs(tree[k][i], depth + 1);
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n - 1; ++i) {
scanf("%d %d", &a, &b);
tree[a].push_back(b);
tree[b].push_back(a);
}
for (int i = 1; i <= n; ++i)
if (!marked[i]) {
dfs(i, 1);
++components;
}
if (components != 1) {
printf("Error: %d components", components);
return 0;
}
ss = s;
s.clear();
maxdepth = 1;
fill(marked, marked + 10010, 0);
dfs(*ss.begin(), 1);
for (auto it : s)ss.insert(it);
for (auto it : ss)printf("%d\n", it);
return 0;
}