洛谷 [P2296] 寻找道路

反向BFS预处理,求出所有符合题意的点,再正向BFS,(注意对于边权恒为一的点,BFS,比SPFA高效)

输入时n与m分清

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN=10005,MAXM=2000005;
int read(){
    int rv=0,fh=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-') fh=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        rv=(rv<<1)+(rv<<3)+c-'0';
        c=getchar();
    }
    return fh*rv;
}
int head[MAXN],rhead[MAXN],n,m,s,t,nume,rnume,tot=-1,path[MAXN];
bool f[MAXN],use[MAXN];
struct edge{
    int to,nxt;
}e[MAXM],re[MAXM];
void adde(int from,int to){
    e[++nume].to=to;
    e[nume].nxt=head[from];
    head[from]=nume;
}
void radde(int from,int to){
    re[++rnume].to=to;
    re[rnume].nxt=rhead[from];
    rhead[from]=rnume;
}
void bfs(){
    queue <int> q;
    q.push(t);
    f[t]=1;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int i=rhead[u];i;i=re[i].nxt){
            int v=re[i].to;
            if(!f[v]){
                f[v]=1;
                q.push(v);
            }
        }
    } 
}
/*void dfs(int u){
    f[u]=1;
    for(int i=rhead[u];i;i=re[i].nxt){
            int v=re[i].to;
            if(!f[v]){
                dfs(v);

            }
    }
}*/
void bfs2(){
    queue <int> q;
    q.push(s);
    f[s]=1;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int i=head[u];i;i=e[i].nxt){
            int v=e[i].to;
            if(!f[v]&&!use[v]){
                f[v]=1;
                q.push(v);
                path[v]=path[u]+1;
                if(v==t){
                    tot=path[v];
                    return;
                }
            }
        }
    }
}
int main(){
//  freopen("in.txt","r",stdin);
    n=read();m=read();
    for(int i=1;i<=m;i++){
        int u=read(),v=read();
        //cout<<u<<" "<<v<<endl;
        adde(u,v);radde(v,u);
    }
    s=read();t=read();
    bfs();
    for(int i=1;i<=n;i++){
        if(!f[i]){
            //use[i]=1;
            for(int j=rhead[i];j;j=re[j].nxt){
                use[re[j].to]=1;
            }
        }
    }
    //for(int i=1;i<=n;i++) if(!f[i]) printf("%d ",i);
    memset(f,0,sizeof(f));
    //for(int i=1;i<=n;i++) printf("%d ",f[i]);
    bfs2();
    cout<<tot;
//  fclose(stdin);
    return 0;
}

P2296

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值