天梯赛练习题 L3-008 喊山(bfs)

发布时间 2023-04-10 21:27:55作者: 高尔赛凡尔娟

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

输入样例:
7 5 4
1 2
2 3
3 1
4 5
5 6
1 4 5 7
输出样例:
2
6
4
0
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;
const LL MAXN=1e18,MINN=-MAXN,INF=0x3f3f3f3f;
const LL N=1e6+10,M=2023;
const LL mod=100000007;
const double PI=3.1415926535;
#define endl '\n'
LL n,m,k,maxn=0,a[N];
LL dist[N];
vector<LL> v[N];
bool vis[N];
int bfs(int x)
{
    memset(vis,false,sizeof vis);
    memset(dist,0,sizeof dist);
    queue<LL> q;
    q.push(x);
    dist[x]=0;
    vis[x]=true;
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        for(int i=0;i<v[t].size();i++)
        {
            if(vis[v[t][i]]==true) continue;
            vis[v[t][i]]=true;
            q.push(v[t][i]);
            dist[v[t][i]]=dist[t]+1;
            maxn=max(maxn,dist[v[t][i]]);
        }
    }
}
int main()
{
    cin.tie(0); cout.tie(0); ios::sync_with_stdio(false);
    LL T=1;
    //cin>>T;
    while(T--)
    {
        cin>>n>>m>>k;
        while(m--)
        {
            LL x,y;
            cin>>x>>y;
            v[x].push_back(y);
            v[y].push_back(x);
        }
        while(k--)
        {
            LL x;
            cin>>x;
            if(v[x].size()==0)
            {
                cout<<"0"<<endl;
                continue;
            }
            maxn=0;
            bfs(x);
            for(int i=1;i<=n;i++)
            {
                if(dist[i]==maxn)
                {
                    cout<<i<<endl;
                    break;
                }
            }
        }
    }
    return 0;
}