PAT 1021. Deepest Root (25)

DFS once, select the farthest point and DFS again, the union is what is required.

 
  
#include <cstdio>
#include<string.h>
#include<string>
#include<map>
#include<vector>
#include<stdio.h>
#include<set>
#include<iostream>
#include <algorithm>
using namespace std;

vector<int> edge[10005];
int mark[10005]={0};
int deepest=-1;
int path[10005];
int p=0;
int tmp;

void dfs(int x,int deep)
{
    mark[x]=1;
    if(deep>deepest)
    {
        deepest=deep;
        path[0]=x;
        p=1;
    }
    else if(deep==deepest)
    {
        path[p++]=x;
    }
    for(int i=0;i<edge[x].size();i++)
    {
        if(mark[edge[x][i]]==0) dfs(edge[x][i],deep+1);
    }
}


intmain()
{
    int n;
    cin>>n;
   for(int i=1;i<n;i++)
   {
       int x,y;
       scanf("%d %d",&x,&y);
       edge[x].push_back(y);
       edge[y].push_back(x);
   }
     dfs(1,0);
     int flag=0;
     for(int i=1;i<=n;i++)
       if(mark[i]==0) {flag=1;break;}

     if(flag==1)
     {
         int cnt=1;
         for(int i=1;i<=n;i++)
          if(mark[i]==0)
         {
             cnt++;dfs(i,0);
         }

         printf("Error: %d components",cnt);
     }
     else
     {
         tmp=path[p-1];
         set<int> S;
         for(int i=0;i<p;i++)
         S.insert(path[i]);
         p=0;
         memset(mark,0,sizeof(mark));
         dfs(tmp,0);
         for(int i=0;i<p;i++)
         S.insert(path[i]);
         for(set<int>::iterator it=S.begin();it!=S.end();it++)
         {
             cout<<*it<<endl;
         }

     }
    return 0;
}


 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325754911&siteId=291194637