Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤104) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N−1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.
Output Specification:
For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.
思路如下:
- 判断是否为树。由于题目已经表明,只有N-1条边,所以必然是数,或者是带环路的的森林,这样问题就转换为判断连通块的个数。
- 第二个问题就是计算最大深度的问题,由于题目要求输出所有的最大深度的点,这里使用distance[k]来表示k点为root的最大深度。再设置一个index[k]数组,判断k时候为最大值。最后遍历index数组,输出所有的最大值的序号。
下面是AC的 代码:
这里没有使用using namespace std; 是因为会和全局变量冲突
#include <stdio.h>
#include <algorithm>
#include <vector>
using std::vector;
using std::fill;
const int maxn = 1e4 + 10;
vector<vector<int>> G;
bool isvisit[maxn];
int n, distance[maxn] = {0};
void DFS(int index) {
isvisit[index] = true;
if (G[index].size() == 0) return;
else {
for (int i = 0; i < G[index].size(); i++) {
if (isvisit[G[index][i]] == false)
DFS(G[index][i]);
}
}
}
//计算index为root节点的最远距离
void cal(int index,int height,int k) { //k为当前节点
isvisit[k] = true;
height++;
if (height > distance[index])
distance[index] = height;
for (int i = 0; i < G[k].size(); i++) {
if(isvisit[G[k][i]]==false)
cal(index, height, G[k][i]);
}
return;
}
int main() {
fill(isvisit, isvisit + maxn, false);
int a,b;
scanf("%d", &n);
G.resize(n + 1);
for (int i = 1; i < n; i++) {
scanf("%d %d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (isvisit[i] == false) {
cnt++;
DFS(i);
}
} //连通块
if (cnt > 1) {
printf("Error: %d components", cnt);
return 0;
}
for (int i = 1; i <= n; i++) {
fill(isvisit, isvisit + maxn, false);
cal(i, 0, i);
}
vector<bool> ismax(n + 1);
fill(ismax.begin(), ismax.end(), true);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (distance[i] < distance[j]) {
ismax[i] = false;
break;
}
}
}
for (int i = 1; i <= n; i++)
if (ismax[i]) printf("%d\n", i);
return 0;
}