题目内容
具体题目见https://www.patest.cn/contests/pat-a-practise/1021
分析内容
1.判断连通分量的个数,可以用dfs,可以用并查集,也可以用bfs
2.为什么选择bfs,因为题目中要求转化成树,并且求出树最大层次的根节点,这需要用到层次遍历,因此bfs更好。因为bfs自身就用到队列。
3.对每个节点进行一个bfs,才能求出这个节点对应的层次。
代码内容
#include <iostream>
#include <vector>
#include <queue>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
const int NUM = 10000+5;
bool visited[NUM]={false};
int level[NUM]={0},level2[NUM]={0};
vector < vector<int> > v(NUM);
int bfs(int root){//进行bfs
queue<int> q;
int now;
q.push(root);
visited[root]=true;
int ceng = 0;
while(!q.empty()){
int size = q.size();
ceng++;
for(int j=0;j<size;j++){
now = q.front();
q.pop();
for(int i=0;i<v[now].size();i++){
int t = v[now][i];
if(visited[t]==false){
visited[t] = true;
q.push(t);
}
}
}
}
return ceng;
}
int main(int argc, char *argv[]) {
int n,count=0;
cin>>n;
for(int i=0;i<n-1;i++){//构建图的邻接表
int x,y;
cin>>x>>y;
v[x].push_back(y);
v[y].push_back(x);
}
for(int i=1;i<=n;i++){//找连通分量
if(visited[i]==false){
bfs(i);
count++;
}
}
int i=1;
int res[n+1];
if(count>1){
cout<<"Error: "<<count<<" components"<<endl;
}
else{//求每个节点的层次
int MAX = -1;
for(int k=1;k<=n;k++){
for(int j=0;j<NUM;j++){
visited[j]=false;
}
int t = bfs(k);
res[i++]=t;
if(MAX<t){
MAX = t;
}
}
for(int j=1;j<=n;j++){//输出最大层次对应的节点编号
if(res[j]==MAX){
cout<<j<<endl;
}
}
}
return 0;
}