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.
Sample Input 1:5 1 2 1 3 1 4 2 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
#include <iostream>#include <map>#include <vector>using namespace std;int n;int a[10001][10001];int mark[10001];int components = 0;int maxLevel = 0;vector<int> elements;void dfs(int root, int i, int level) {if (level > maxLevel) {maxLevel = level;elements.clear();elements.push_back(root);}else if (level == maxLevel) {if (root != elements[elements.size() - 1])elements.push_back(root);}for (int j = 1; j <= n; j++) {if (a[j][i] > 0 && j != i&&mark[j] == 0) {mark[j] = 1;dfs(root, j, level + 1);}}}void CalcComp(int p) {for (int i = 1; i <= n; i++) {if (a[p][i] > 0 && p != i&&mark[i] == 0) {mark[i] = 1;CalcComp(i);}}}int main(void) {cin >> n;for (int i = 1; i < n; i++) {int u, v;cin >> u >> v;a[u][v] = 1;a[v][u] = 1;}while (true){int p, cnt = 0;for (int i = 1; i <= n; i++) {if (mark[i] == 0) {components++;mark[i]++;p = i;break;}else {cnt++;}}if (cnt == n) {cnt = 0;break;}CalcComp(p);}if (components > 1) {cout << "Error: " << components << " components";return 0;}if (n <= 15) {for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++)mark[j] = 0;mark[i] = 1;dfs(i, i, 1);}}else {for (int i = 1; i <= n; i++) {int cnt = 0;for (int j = 1; j <= n; j++) {cnt += a[i][j];}if (cnt == 1)elements.push_back(i);cnt = 0;}}for (int i = 0; i < elements.size(); i++) {cout << elements[i] << endl;}return 0;}
原文:http://www.cnblogs.com/zzandliz/p/5023075.html