树的直径19-12-4(BFS)

#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
#include<cmath>
using namespace std;
int data[20][20];
int route[20];
bool vis[20];
int res[20];
int n;
int BFS(int i)
{
  int end;
  memset(res,0,sizeof(res));
  memset(route,0,sizeof(route));
  memset(vis,false,sizeof(vis));
  queue<int>q;
  q.push(i);
  res[i]=1;vis[i]=1;
  while(!q.empty()){
    int root=q.front();
    for(int j = 1 ; j <= n ; j++){
      if(data[root][j] && vis[j]!=1){//确保不访问到父亲节点
        q.push(j);
        route[j]=root;//每个儿子点记录它的父亲
        vis[j]=1;//标记
        res[j]=res[root]+1;//距离起点的步数,最终即求res[]内的max
      }
    }
    end=q.front();
    q.pop();
  }
  return end;//返回最后一个子节点
}
int main(){
  cin >> n;
  int a,b;
  for(int i = 1 ; i <= n-1 ; i++){
    cin >> a >> b;
    data[a][b]=1;
    data[b][a]=1;
  }
  int temp=BFS(1);
  int t=BFS(temp);//两次BFS找到直径,也即最长路径
  int ans=res[t];
  cout << ans << endl;
  while(t!=temp){
    cout << t << " ";
    t=route[t];//从子节点往前找,最后走回初始节点
  }
  cout << temp << endl;//输出初始节点
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/ecustlegendn324/p/11982132.html