1021 Deepest Root (25)(25 分)

1021 Deepest Root (25)(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 (<=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 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

很棒的一道题
题干很简练,找到使得整棵树深度最大的根节点
明确先找连通分量的个数,找的过程中就可以记录叶子节点了

两种situation
①不连通 输出个数
②得到一批叶子节点
比如
1 2
2 3
3 4
图自己画一下吧
从一出发会得到3,4三个叶子节点
随便取个节点3,再次dfs,得到1,4两个节点
取个并集 1,3,4三个节点都可以作为根
还有情况如
1 2
2 3
3 4
2 5
5 6
从1出发得到4,6
从4出发,得到6
并集4,6

Prove:
假设最终root为U{1,2,3,4,5 }(全局解)
随便取个点A,第一次dfs可以得到集合S∈U (局部解)如果S中有一个元素B不在U中,意味着
AB=AS1=AS2=AS3… >A(elements not in S)
最长路径=AB+AS1=AB+AS2=AB+AS3=BS1=BS2=BS3
意味着B理应为U的一部分
与假设矛盾
故第一次dfs得到的解是U的一部分

这样证明应该比较清晰了

#include <bits/stdc++.h>
using namespace std;
map<int, vector<int> > mymap;
vector<int> v;
set <int> s;//保存叶子节点,既是终点也是起点呐,就像人生的路起点亦是终点,终点亦是起点
int mm;
int vis[100002];
void dfs(int x,int step){//深度优先搜索
    vis[x]=1;
    if(step>mm){//找到路径最大的,更新
        mm=step;
        v.clear();
        v.push_back(x);
    }
    else if(step==mm){//多条最大路径
        v.push_back(x);
    }
    for(int i=0;i<mymap[x].size();i++){
        if(!vis[mymap[x][i]]){
            dfs(mymap[x][i],step+1);
        }
    }
}
int main(){
    int N;
    cin>>N;
    for(int i=1;i<=N-1;i++){
        int a,b;
        cin>>a>>b;
        mymap[a].push_back(b);
        mymap[b].push_back(a);
    }
    int temp=0;
    int K=0;
    for(int i=1;i<=N;i++){
        if(!vis[i]){
            dfs(i,0);
            if(i==1){//第一个节点开始访问的所有叶子节点
                for(int j=0;j<v.size();j++){
                    if(j==0) temp=v[j];//随便取一个作为起点
                    s.insert(v[j]);//塞进set中
                }
            }
            K++;        
        }
    }//计算连通分量个数
    if(K==1){
        memset(vis,0,sizeof(vis));
        v.clear();//清空原来的数组
        dfs(temp,0);//从一个叶子开始搜索
        for(int i=0;i<v.size();i++){//set保证不会重复
            s.insert(v[i]);
        }
        set<int>::iterator It;
        for(It=s.begin();It!=s.end();It++){
            printf("%d\n",*It);
        }
    }
    else printf("Error: %d components\n",K );
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38677814/article/details/80859998