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 (<=10000) 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.
voiddfs(int cur){ for (int i = 0; i < m[cur].size(); i++) { if (visited[m[cur][i]] == 0) { visited[m[cur][i]] = 1; dfs(m[cur][i]); } } }
intgetMax(int n){ int maxValue = level[1]; for (int i = 2; i <= n; i++) { if (level[i] > maxValue) { maxValue = level[i]; } } return maxValue; }
intbfs(int cur, int n){ queue<int> r; r.push(cur); fill(visited, visited + n + 1, 0); fill(level, level + n + 1, 0); level[cur] = 1; visited[cur] = 1; while (r.size() != 0) { cur = r.front(); r.pop(); for (int i = 0; i < m[cur].size(); i++) { int c = m[cur][i]; if (visited[c] == 0) { visited[c] = 1; r.push(c); level[c] = level[cur] + 1; } } } returngetMax(n); }
intmain(){ int n = 0; scanf("%d", &n); m.resize(n + 1); for (int i = 1; i < n; i++) { int a = 0, b = 0; scanf("%d %d", &a, &b); m[a].push_back(b); m[b].push_back(a); }
int k = 0; visited = newint[n + 1]; for (int i = 1; i <= n; i++) { if (visited[i] == 0) { visited[i] = 1; dfs(i); k++; } }
if (k != 1) printf("Error: %d components\n", k); else { level = newint[n + 1]; int maxValue = -1; vector<int> ans; for (int i = 1; i <= n; i++) { int v = bfs(i, n); if (v > maxValue) { ans.clear(); ans.push_back(i); maxValue = v; } elseif (v == maxValue) { ans.push_back(i); } } for (int i = 0; i < ans.size(); i++) { printf("%d\n", ans[i]); } } delete[] level; delete[] visited; return0; }