PAT 甲级1021. Deepest Root (25)

来源:互联网 发布:淘宝货到付款买家拒签 编辑:程序博客网 时间:2024/06/05 16:26

题目:

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:
51 21 31 42 5
Sample Output 1:
345
Sample Input 2:
51 31 42 53 4
Sample Output 2:
Error: 2 components
思路:

1.先用并查集考察是否为同一树

2.再用深度优先搜索查找最深的节点

注意:

1.不能用邻接节点,否则会有测试点超时


代码:

#include<string.h>#include<iostream>#include<vector>#include<algorithm>using namespace std;const int Max = 10001;vector<int> linkmap[Max];int node[Max] = { 0 };//union-find: find rootint findroot(int r){if (r != node[r]){findroot(node[r]);}elsereturn r;};//union-find: unionvoid unionnode(int r1, int r2){node[r1] = findroot(r1);node[r2] = findroot(r2);if (node[r1] != node[r2]){if(node[r1]<node[r2])     node[r2] = node[r1];else node[r1] = node[r2];}return;};//depth first searchint visit[Max] = { 0 };int dfs(int deep,int n,int N){int i,d,maxd,tmp;maxd = deep;visit[n] = 1; //mark the nodefor (i = 0; i <linkmap[n].size(); ++i){tmp = linkmap[n][i];if (!visit[tmp]){d=dfs(deep + 1, tmp, N);if (d > maxd)maxd = d;}}return maxd;}int main(){int N;cin >> N;if (N == 1){cout << 1 << endl;}else{//inputint i, n1, n2;for (i = 1; i <= N; ++i){node[i] = i;}for (i = 1; i < N; ++i){cin >> n1 >> n2;linkmap[n1].push_back(n2);linkmap[n2].push_back(n1);unionnode(n1, n2);}//use union-find int comp = 0;for (i = 1; i <= N; ++i){if (i == node[i])comp++;}if (comp > 1){cout << "Error: " << comp << " components" << endl;}else{int j;vector<int> result;int R = 0;int depth;for (i = 1; i <= N; ++i){if (linkmap[i].size()==1){memset(visit, 0, sizeof(visit));depth = dfs(0, i, N);//find the depthif (depth > R){R = depth;result.clear();result.push_back(i);}else if (depth == R){result.push_back(i);}}}sort(result.begin(), result.end());for (i = 0; i < result.size(); ++i)cout << result[i] << endl;}}system("pause");return 0;}


原创粉丝点击