其他分享
首页 > 其他分享> > PAT Advanced 1021 Deepest Root(25)

PAT Advanced 1021 Deepest Root(25)

作者:互联网

题目描述:

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 (≤104) 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 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

算法描述:DFS

题目大意:

给出n个结点,和n-1条边
若是树,则输出能构成最大高度的所有首尾结点;否则输出连通块的数量

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

const int N = 10010;
set<int> ans;
vector<int> v[N];
vector<int> max_point;
bool st[N]; 
int max_len = 0;
// 遍历所有结点  求连通块数量
void dfs(int cur)
{
    if(st[cur])  return;
    st[cur] = 1;
    for(int i : v[cur])
        dfs(i);
}
// 找最长路径  
void _dfs(int cur, int len)
{
    if(st[cur])    return;
    st[cur] = 1;
    if(len > max_len)
    {
        max_len = len;
        max_point.clear();
        max_point.push_back(cur);
    }
    else if(len == max_len) max_point.push_back(cur);
    for(int i : v[cur])
    {
        _dfs(i, len + 1);
    }
}

int main()
{
    int n;
    cin >> n;
    for(int i = 1 ; i < n ; i ++)
    {
        int j, k;
        cin >> j >> k;
        v[j].push_back(k);
        v[k].push_back(j);
    }
    
    int cnt = 0;
    for(int i = 1 ; i <= n ; i ++)
        if(!st[i])
        {
            cnt ++;
            dfs(i);
        }
    // 连通块cnt为1时是树
    if(cnt != 1) 
    {
        printf("Error: %d components", cnt);
    }
    else
    { //先由根结点出发找到离根结点最远的结点(不一定唯一)并放入set
        memset(st, 0, sizeof st);
        _dfs(1, 0);
        for(int x : max_point)  ans.insert(x);
        // 再由离根最远的结点(任一)出发找最远的结点(不一定唯一)并放入set
        max_point.clear();
        max_len = 0;
        memset(st, 0, sizeof st);
        _dfs(*ans.begin(), 0);
        for(int x : max_point)  ans.insert(x);
        
        for(int x : ans)    cout << x << endl;
    }
    
    return 0;
}

标签:25,1021,cur,int,max,len,st,Deepest,root
来源: https://www.cnblogs.com/yztozju/p/16608929.html