1. 程式人生 > >1021 Deepest Root (25 分)

1021 Deepest Root (25 分)

1021 Deepest Root (25 分)

A graph which is connected and acyclic can be considered a tree. The hight 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 N1 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

思路-:
  求出連通圖每一個頂點所對應的最大深度,存入到一個數組中,在輸出時,只需要遍歷這個陣列,輸出和最大深度相同的結點下標為止。
思路二:
  從任意一個頂點開始遍歷,在這次遍歷過程中,記錄下深度最大的頂點小標(可能不止一個),然後從上次遍歷記錄下的頂點下標(其中任何一個)開始進行深度
優先遍歷,把具有最大高度的頂點編號記錄下來(可能不止一個),兩次遍歷的並集即為所求。
技巧:
  使用c++中的vector構造鄰接表,這樣的時間複雜度是o(e+v)(頂點數和邊數的和),當輸入較大時,無論時間複雜度還是空間複雜度都比使用鄰接矩陣要小。
#include<iostream>


#include<cstdio>
#include<string.h>

#include<vector>
#include<set>
using namespace std;

bool visited[10001];
int n;
vector<int> temp;
vector<vector<int>> v;//這樣的實現是使用鄰接表
set<int> s;
int d=0;
void dfs2(int start,int deep)
{
    d=max(deep,d);
    for(int i=0; i<v[start].size(); i++)
    {
        if(visited[v[start][i]]==false)
        {
            visited[v[start][i]]=true;
            dfs2(v[start][i],deep+1);
        }
    }
}

int main()
{
    scanf("%d",&n);
    v.resize(n+1);
    for(int i=0; i<n-1; i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        v[x].push_back(y);
        v[y].push_back(x);
    }
    int num=0;
    int s1=1;
    fill(visited,visited+10001,false);
    for(int i=1; i<n+1; i++)
    {
        if(visited[i]==false)
        {
            num++;
            visited[i]=true;
            dfs2(i,0);
        }

    }
    if(num>1)
    {
        printf("Error: %d components",num);

    }
    else
    {
        int deep[n+1];
        int maxValue=0;
        for(int i=1;i<n+1;i++)
        {
            d=0;
            fill(visited,visited+10001,false);
            visited[i]=true;
            dfs2(i,0);
            deep[i]=d;
            maxValue=max(d,maxValue);
        }
        for(int i=1;i<n+1;i++)
            if(deep[i]==maxValue)
                printf("%d\n",i);

    }
    return 0;
}