L3-008 喊山 (30分)——BFS+链式前向星

题目链接
https://pintia.cn/problem-sets/994805046380707840/problems/994805050709229568
思路
      思路不难,存图,根据查询点遍历,维护深度和编号最小点,但是这题被卡的恶心,最开始我是用邻接矩阵+dfs写的,超时两个点,wa一个点,然后改成链式前向星+bfs,wa两个点,改了半天,最后发现只要把N从1e4调成2e4就过了。

BFS代码

#include<bits/stdc++.h>
using namespace std;

const int N = 2e4+5;
typedef pair<int,int> PII;

int n,m,k;
int e[N],ne[N],h[N],idx;
int vis[N];
int MAX=0,res=1e5;

void add(int a,int b)
{
    
    
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs(int u)
{
    
    
    queue<PII> q;
    q.push({
    
    u,0});
    vis[u]=1;

    while(q.size())
    {
    
    
        auto t=q.front();
        q.pop();

        if(t.second>MAX)
        {
    
    
            MAX=t.second;
            res=t.first;
        }
        else if(t.second==MAX&&res>t.first)
        {
    
    
            res=t.first;
        }
        for(int i=h[t.first];i!=-1;i=ne[i])
        {
    
    
            int j=e[i];
            if(!vis[j])
            {
    
    
                q.push({
    
    j,t.second+1});
                vis[j]=1;
            }
        }
    }
}

int main()
{
    
    
	cin>>n>>m>>k;
    memset(h,-1,sizeof(h));
    for(int i=1;i<=m;i++)
    {
    
    
        int a,b;
        cin>>a>>b;
        add(a,b);
        add(b,a);
    }
    int x[k];
    for(int i=0;i<k;i++)
    {
    
    
        cin>>x[i];
    }
    for(int i=0;i<k;i++)
    {
    
    
        bfs(x[i]);
        if(!MAX)
        {
    
    
            printf("0\n");
        }
        else
        {
    
    
            cout<<res<<'\n';
        }
        res=1e5;
        MAX=0;
        memset(vis,0,sizeof(vis));
    }
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Star_Platinum14/article/details/112727736