Luogu P11280 GFOI Round 2 Jom & Terry 题解 [ 黄 ] [ BFS ]

Jom & Terry讲个笑话,我赛时被诈骗了。

思路

先放结论:如果 Terry 到终点的距离小于等于 Jom 到终点的距离,那么 Terry 一定不会被抓。

为啥呢,因为不管 Jom 堵哪里,Jom 总要比 Terry 早到达某个最短路径上的点。而因为 Jom 更早到,所以本来就可以直接到终点去堵 Terry,根本不需要在路上去堵他,证毕。

因为终点固定,又是无向图,所以以终点为起点 BFS 一遍即可求出其他点到终点的距离,时间复杂度 O(n+q)

代码

#include <bits/stdc++.h>
#define fi first
#define se second
#define lc (p<<1)
#define rc ((p<<1)|1)
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
#define lc(x) (tr[x].ls)
#define rc(x) (tr[x].rs)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
using pi=pair<int,int>;
const int N=1000005;
int n,m,r,q,d[N];
vector<int>g[N];
void bfs(int s)
{
    queue<int>q;
    memset(d,0x3f,sizeof(d));
    d[s]=0;
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(auto v:g[u])
        {
            if(d[v]>=0x3f3f3f3f)
            {
                d[v]=d[u]+1;
                q.push(v);
            }
        }
    }
}
int main()
{
    //freopen("sample.in","r",stdin);
    //freopen("sample.out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m>>r;
    for(int i=1;i<=m;i++)
    {
        int u,v;
        cin>>u>>v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    bfs(r);
    cout<<"I'm here!\n";
    cin>>q;
    while(q--)
    {
        int a,b;
        cin>>a>>b;
        if(d[a]<=d[b])cout<<"Terry\n";
        else cout<<"Jom\n";
    }
    return 0;
}
posted @   KS_Fszha  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
点击右上角即可分享
微信分享提示