NOIP 2014 寻找道路

本文介绍了一种使用双向BFS求解图中两点间最短路径的方法。首先进行反向搜索,移除不可达节点及其邻接点;接着进行正向搜索找到最短路径。文中提供了一个完整的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

评测传送

先反向跑一边bfs,然后将到达不了的点以及它的邻接点删掉。(注意只删一层)
然后再正向跑一遍bfs就可以了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<queue>
using namespace std;
const int N=10009;
const int M=200009;
int head[N],nxt[M],to[M],tot;
int head2[N],nxt2[M],to2[M],tot2;
int n,m,s,t,ans;
bool used[N],vis[N];
struct H{
    int x,step;
};
void add(int x,int y)
{
    to[++tot]=y;
    nxt[tot]=head[x];
    head[x]=tot;
}
void add2(int x,int y)
{
    to2[++tot2]=y;
    nxt2[tot2]=head2[x];
    head2[x]=tot2;
}
void color()
{
    queue <int> q;
    q.push(t);
    used[t]=1;
    while(!q.empty())
    {
        int k=q.front();q.pop();
        for(int i=head2[k];i;i=nxt2[i])
        {
            if(!used[to2[i]])
            {
                used[to2[i]]=1;
                q.push(to2[i]);
            }
        }
    }
    for(int x=1;x<=n;x++)
    if(!used[x])
    {
        for(int i=head2[x];i;i=nxt2[i])
        {
            //used[to2[i]]=0;一定不是这样!!!我就是因为这个错误WA了8个点
            vis[to2[i]]=1;
        }
    }
}
int bfs()
{
    queue <H> q;
    q.push((H){s,0});
    vis[s]=1;
    while(!q.empty())
    {
        H k=q.front();q.pop();
        if(k.x==t) return k.step; 
        for(int i=head[k.x];i;i=nxt[i])
        {
            if(used[to[i]]&&!vis[to[i]])
            vis[to[i]]=1,q.push((H){to[i],k.step+1}); 
        }
    }
    return -1;
}
int main()
{
    //freopen("road.in","r",stdin);
    //freopen("road.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        add(x,y);add2(y,x);
    }
    scanf("%d%d",&s,&t);
    color();
    ans=bfs();
    printf("%d\n",ans);
    //printf("%d",clock());
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值