思路:
利用深度优先搜索 DFS,获得连通分量的个数,若个数大于 1 ,则输出错误消息;
若连通分量分数为1,则利用广度优先搜索 BFS 获取根的对应深度,从中输出满足最大值的结点。
1021 Deepest Root (25 point(s))
A graph which is connected and acyclic can be considered a tree. The height of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.
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.
Sample Input 1:
5
1 2
1 3
1 4
2 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components
Example:
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
typedef int Vertex;
struct Graph {
int Nv;
int Ne;
vector<vector<int>> G;
};
void DFS(Graph &G, Vertex v, vector<bool> &Visited)
{
Visited[v] = true;
for(auto &x : G.G[v]) if(!Visited[x]) DFS(G, x, Visited);
}
int BFS(Graph &G, Vertex v)
{
vector<int> Depth(G.Nv+1, 0);
queue<Vertex> Q;
Q.push(v);
Depth[v] = 1;
while(!Q.empty()) {
v = Q.front();
for(auto &x : G.G[v]) {
if(Depth[x] == 0) {
Depth[x] = Depth[v] + 1;
Q.push(x);
}
}
Q.pop();
}
return *max_element(Depth.begin(), Depth.end());
}
int main()
{
int N;
cin >> N;
Graph G;
G.Nv = N, G.Ne = N - 1, G.G.resize(N+1);
for(int i = 0; i < G.Ne; i++) {
int v1, v2;
cin >> v1 >> v2;
G.G[v1].push_back(v2);
G.G[v2].push_back(v1);
}
vector<bool> Visited(G.Nv+1, 0);
int K = 0;
for(int i = 1; i <= G.Nv; i++) {
if(Visited[i]) continue;
DFS(G, i, Visited);
K++;
}
if(K != 1) {
cout << "Error: " << K << " components\n";
return 0;
}
vector<vector<int>> result(G.Nv+1);
for(int i = 1; i <= G.Nv; i++) result[BFS(G, i)].push_back(i);
for(auto x = result.rbegin(); x != result.rend(); x++) {
if(!x->empty()) {
for(auto &y : *x) cout << y << endl;
break;
}
}
}