L3-008 喊山 (30 分)

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

思路:bfs

#include 
#include 
#include 
#include 
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;
}

你可能感兴趣的:(算法,算法)