【BFS层次遍历+last变量】一遍AC~
思路和之前的一样,使用BFS+last变量进行层次遍历就可以求出深度。遍历以每个结点做根的情况就可以顺利地得到一个深度啦!其他的就是基本操作了,不多b。
参考之前写过的一道题的思路:PAT1004
#include <bits/stdc++.h>
using namespace std;
int N;
vector<int> v[10010];
bool vst[10010];
int dpth[10010];
int BFS(int n)
{
int depth=0;
int last=n;
queue<int> q;
q.push(n);
while(!q.empty())
{
int temp=q.front();
q.pop();
vst[temp]=true;
for(int i=0;i<v[temp].size();i++)
{
if(!vst[v[temp][i]])
q.push(v[temp][i]);
}
if(temp==last)
{
last=q.back(); //update 'last'
depth++;
}
}
return depth;
}
int main(void)
{
int si,di,max=0,cmpnt=0;
scanf("%d",&N);
for(int i=0;i<N-1;i++)
{
scanf("%d%d",&si,&di);
v[si].push_back(di);
v[di].push_back(si);
}
memset(vst,false,sizeof(vst));
for(int i=1;i<=N;i++)
if(!vst[i])
{
BFS(i);cmpnt++;
}
if(cmpnt!=1) printf("Error: %d components\n",cmpnt);
else
{
for(int i=1;i<=N;i++)
{
memset(vst,false,sizeof(vst));
dpth[i]=BFS(i);
if(dpth[i]>max) max=dpth[i];
}
for(int i=1;i<=N;i++)
if(dpth[i]==max) printf("%d\n",i);
}
}