判断图是否都连接构成树,求使树高最大的根
实际上求图上两点间最大距离
先用并查集判断共有几个部分
bfs求距离
先任取一点开始bfs,得到最远的叶节点
以此叶节点再bfs可得
实际上求图上两点间最大距离
先用并查集判断共有几个部分
bfs求距离
先任取一点开始bfs,得到最远的叶节点
以此叶节点再bfs可得
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<queue>
#include<set>
#include<memory.h>
#include<algorithm>
#define MAXV 10001
int dist[MAXV]; // store distance
int points[MAXV]; // store root
vector<int> adj_list[MAXV]; //store neighbor
//return the max distance
int bfs(int start , int V)
{
memset(dist,-1,sizeof(dist));
dist[start] = 0;
queue<int> q;
q.push(start);
int dmax = 0;
while(!q.empty())
{
int now = q.front();
q.pop();
int d = dist[now];
for(int i = 0; i < adj_list[now].size(); i++)
{
//not visit before
if(dist[ adj_list[now][i] ] == -1)
{
dist[ adj_list[now][i] ] = d +1;
q.push(adj_list[now][i]);
}
}
if(d > dmax)
{
dmax = d;
}
}
return dmax;
}
int find(int pos)
{
if(points[pos] == -1)
return pos;
return points[pos] = find(points[pos]);
}
int merge(int a,int b)
{
int roota = find(a);
int rootb = find(b);
if(roota == rootb)
return 0;
points[roota] = rootb;
return 1;
}
int main()
{
int N;
int a;
int b;
cin>>N;
memset(points,-1,sizeof(points));
for(int i=0;i<N-1;i++)
{
cin>>a;
cin>>b;
merge(a,b);
adj_list[a].push_back(b);
adj_list[b].push_back(a);
}
//count components
int cnt = 0;
for(int i=1;i<=N;i++)
{
if(points[i]==-1)
cnt++;
}
set<int> first;
set<int> total;
if(cnt != 1)
{
cout<<"Error: "<<cnt<<" components"<<endl;
return 0;
}
else
{
int dmax = bfs(1,N);
for(int i = 1 ;i <= N;i++ )
{
if(dist[i] == dmax)
{
first.insert(i);
total.insert(i);
}
}
dmax = bfs(*first.begin(),N);
for(int i = 1 ;i <= N;i++ )
{
if(dist[i] == dmax)
{
first.insert(i);
total.insert(i);
}
}
for( set<int>::iterator it = total.begin() ; it != total.end() ; ++it )
{
cout << *it << endl;
}
}
}