码迷,mamicode.com
首页 > 其他好文 > 详细

洛谷 [P2296] 寻找道路

时间:2017-11-20 23:20:14      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:getc   out   close   stdin   mem   head   push   open   ++   

反向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

洛谷 [P2296] 寻找道路

标签:getc   out   close   stdin   mem   head   push   open   ++   

原文地址:http://www.cnblogs.com/Mr-WolframsMgcBox/p/7868386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!