PAT-A-1021. Deepest Root (25)

来源:互联网 发布:laravel 获得sql语句 编辑:程序博客网 时间:2024/05/21 21:49

1021. Deepest Root (25)

时间限制
1500 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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
#include<iostream>#include<cstdio>#include<vector>#include<algorithm>#include<queue>using namespace std;const int maxn = 100010;int n;bool vis[maxn] = { false };vector<int> vex[maxn];int q[maxn];struct node{  int root;  int depth;}v[maxn];int cmp(node a, node b){  if (a.depth != b.depth)    return a.depth > b.depth;  else     return a.root < b.root;}void init(){  for (int i = 1; i < maxn; i++)  {    v[i].depth = 0;    v[i].root = i;  }}void DFS(int n){  vis[n] = true;  for (int i = 0; i < vex[n].size(); i++)  {    int child = vex[n][i];    if (vis[child] != true)      DFS(child);  }}int istu(){  int num = 0;  for (int i = 1; i <= n; i++)  {    if (vis[i] != true)    {      DFS(i);      num++;          }  }  return num;}void refresh(){  for (int i = 1; i <= n; i++)    vis[i] = false;}int BFS(int root){  int depth = 0;  vis[root] = true;  int rear = -1;  int front = -1;  int last = 0;  q[++rear] = root;  while (front <= rear)  {    int p = q[++front];    for (int i = 0; i<vex[p].size(); i++)    {      int child = vex[p][i];      if (vis[child] == false)      {        vis[child] = true;        q[++rear] = child;      }          }    if (last == front)    {      last = rear;      depth++;    }  }  return depth;  }void findvex(){  for (int root = 1; root <= n; root++)  {    refresh();    v[root].depth = BFS(root);  }}int main(){  init();  cin >> n;  int a, b;  for (int i = 0; i < n - 1; i++)  {    cin >> a >> b;    vex[a].push_back(b);    vex[b].push_back(a);  }  int num;  num = istu();  refresh();  if (num == 1)  {    findvex();    sort(v + 1, v + 1 + n, cmp);    cout << v[1].root<<endl;    for (int i = 2; i <=n; i++)    {      if (v[i].depth==v[1].depth)        cout << v[i].root<<endl;    }  }  else  {    printf("Error: %d components\n", num);  }    system("pause");  return 0;}

原创粉丝点击