L3-008 喊山 (30 分)

https://pintia.cn/problem-sets/994805046380707840/problems/994805050709229568

思路:bfs

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 1e4 + 10, M = 1e5 + 10;

int n, m, k;
int h[N], e[M], ne[M], idx;
bool st[N];

void add(int x, int y)
{
    e[idx] = y;
    ne[idx] = h[x];
    h[x] = idx++;
}

int bfs(int a)
{
    memset(st, 0, sizeof(st));
    queue<int>q;
    q.push(a);
    st[a] = true;
    int cnt = 0, ans, res;
    ans = 0x3f3f3f3f;
    res = 0;

    while(q.size())
    {
        int t = q.front();
        q.pop();
        cnt++;

        for(int i = h[t];i != -1; i = ne[i])
        {
            int j = e[i];
            if(!st[j])
            {
                st[j] = true;
                if(res < cnt)
                {
                    res = cnt;
                    ans = j;
                }
                else if(res == cnt)
                {
                    if(ans > j) ans = j;
                }
                q.push(j);
            }
        }
    }

    if(ans == 0x3f3f3f3f) return 0;
    return ans;
}

int main()
{
    memset(h, -1, sizeof(h));
    scanf("%d%d%d", &n, &m, &k);
    while(m--)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        add(a, b);
        add(b, a);
    }
    while(k--)
    {
        int x;
        scanf("%d", &x);
        printf("%d\n", bfs(x));
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值