PAT (Advanced Level) Practice A1021 Deepest Root (25 分)(C++)(甲级)(无向连通图、树、直径)

原题链接:A1021 Deepest Root

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include <ctime>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
using namespace std;

const int MAX = 10010;
int N, M, K, id1, id2;
vector<int> G[MAX];
int Deepest[2*MAX] = {0}, top = 0, tag = 0;//Deepest用来存放可以做根节点的标号
bool visited[MAX] = {0};

void BFS(int v)
{
    queue<int> Q;
    Q.push(v);
    visited[v] = 1;
    int last = v;//last指向本层最后一个
    while(!Q.empty())
    {
        v = Q.front();
        Q.pop();
        Deepest[top++] = v;//Deepest存放扫描的这一层,则函数运行完毕即为最后一层
        for(int i=0; i<(int)G[v].size(); i++)
        {
            if(!visited[G[v][i]])
            {
                visited[G[v][i]] = 1;
                Q.push(G[v][i]);
            }
        }
        if(last == v)
        {
            last = Q.back();
            if(!Q.empty()) top = tag;//非最后一层则重新记录下一次
        }
    }
}

int BFSTraverse()//y从来判断有几个连通分量
{
    int cnt = 0;
    for(int i=1; i<=N; i++)
    {
        if(!visited[i])
        {
            cnt++;
            BFS(i);
        }
    }
    return cnt;
}

int main()
{
    scanf("%d", &N);
    for(int i=1; i<N; i++)
    {
        scanf("%d %d", &id1, &id2);
        G[id1].push_back(id2);
        G[id2].push_back(id1);
    }
    int cnt = BFSTraverse();//大于一个连通分量即不是树,输出错误
    if(cnt > 1) printf("Error: %d components", cnt);
    else
    {
        memset(visited, 0, sizeof(visited));
        BFS(1);//从1出发,找到距离1最远的节点集合,存入Deepest
        tag = top;
        memset(visited, 0, sizeof(visited));
        BFS(Deepest[0]);//再从距离1最远的一个节点出发,扫描到最后一层,存入Deepest
        sort(Deepest, Deepest+top);//排序
        printf("%d\n", Deepest[0]);
        for(int i=1; i<top; i++)//由于两次存入的集合可能出现重复,因此Deepest大小为2*MAX
        {
            if(Deepest[i] != Deepest[i-1])//去除重复数据
            {
                printf("%d\n", Deepest[i]);
            }
        }
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值