1. 程式人生 > >pat1021 Deepest Root

pat1021 Deepest Root

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
#include<cmath>
#include<map>
#include<stack>
#define N 10005
#define ll long long
using namespace std;
vector<int>v[N],ans[2],more;
int max_d,num;
int vis[N],in[N];
void dfs(int u,int dep,int p)
{
  vis[u] = 1;
  if(dep>max_d)
  {
    max_d = dep;
    ans[p].clear();
    if(!in[u])ans[p].push_back(u);
  }
  else if(dep == max_d&&!in[u])ans[p].push_back(u);
  for(int i = 0;i<v[u].size();i++)
  {
    if(vis[v[u][i]])continue;
    dfs(v[u][i],dep+1,p);
  }
}
int main()
{
  int n,i,j,a,b;
  scanf("%d",&n);
    max_d = -1;
    num = 0;
    memset(in,0,sizeof(in));
    memset(vis,0,sizeof(vis));
    for(i = 0;i<n-1;i++)
    {
      scanf("%d%d",&a,&b);
      v[a].push_back(b);
      v[b].push_back(a);
    }
    for(i = 1;i<=n;i++)
    {
      if(!vis[i])
      {
        num++;
        dfs(i,0,0);
      }
    }
    if(num>1)printf("Error: %d components\n",num);
    else
    {
      for(i = 0;i<ans[0].size();i++)in[ans[0][i]] = 1;
          memset(vis,0,sizeof(vis));
        dfs(ans[0][0],0,1);
      for(i = 0;i<ans[1].size();i++)ans[0].push_back(ans[1][i]);
      sort(ans[0].begin(),ans[0].end());
      for(i = 0;i<ans[0].size();i++)printf("%d\n",ans[0][i]);
    }
    return 0;
}