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 (<=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 5Sample Output 1:
3 4 5Sample Input 2:
5 1 3 1 4 2 5 3 4Sample Output 2:
Error: 2 components
https://www.patest.cn/contests/pat-a-practise/1021
https://www.nowcoder.com/questionTerminal/f793ad2e0c7344efa8b6c18d10d4b67b
思路:
参见牛客网。。
好坑。。
CODE:
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
#define N 10010
using namespace std;
vector<int> dist[N];
int gs;
bool fl[N];
int n;
int maxx=0;
int maxn;
int re[N];
int re1[N];
int num1=0;
int nnum1;
void dfs(int no,int flo)
{
if (flo>=maxx)
{
if (flo>maxx) num1=0;
maxx=flo;
re[num1]=no;
num1++;
}
int gs=0;
if(dist[no].empty()) return ;
for (int i=0;i<dist[no].size();i++)
{
if (fl[dist[no][i]]==1) continue;
fl[dist[no][i]]=1;
dfs(dist[no][i],flo+1);
}
return;
}
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
memset(fl,0,sizeof(fl));
cin>>n;
for(int i=0;i<n-1;i++)
{
int u,v;
cin>>u>>v;
u--;
v--;
dist[v].push_back(u);
dist[u].push_back(v);
}
gs=0;
for (int i=0;i<n;i++)
{
if (fl[i]==0)
{
fl[i]=1;
gs++;
dfs(i,0);
}
}
if (gs>1)
{
cout<<"Error: "<<gs<<" components";
}
else
{
memset(fl,0,sizeof(fl));
for (int i=0;i<num1;i++)
{
re1[i]=re[i];
}
int nnn=num1;
num1=0;
maxx=0;
dfs(re[0],0);
for (int i=0;i<num1;i++)
{
re1[nnn+i]=re[i];
}
nnn+=num1;
sort(re1,re1+nnn,cmp);
for (int i=0;i<nnn;i++)
if (i==0 || re1[i]!=re1[i-1])cout<<re1[i]+1<<endl;
}
return 0;
}