pat甲级 1021. Deepest Root(bfs求连通分量)

本文介绍了一种使用广度优先搜索(BFS)解决PAT-A 1021题目的方法,该题目要求计算图的最大层次及对应的根节点。通过构建邻接表并为每个节点执行BFS来确定其层次,最终找出具有最大层次的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目内容
具体题目见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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值