LUOGU P2296 寻找道路 (noip 2014)

传送门

解题思路

首先建一张反图,从终点dfs出哪个点直接或间接相连,然后直接跑最短路,跑的时候判断一下所连的点是否与终点相连。

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#include<vector>

using namespace std;
const int MAXN = 10005;
const int MAXM = 200005;

inline int rd(){
    int x=0,f=1;char ch=getchar();
    while(!isdigit(ch)) {f=ch=='-'?0:1;ch=getchar();}
    while(isdigit(ch))  {x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
    return f?x:-x;
}

int n,m,S,T,head[MAXN],cnt,dis[MAXN];
int to[MAXM],nxt[MAXM];
int head_[MAXN],cnt_,nxt_[MAXM],to_[MAXM];
bool vis[MAXN],ar[MAXN],flag;

struct cmp{
    bool operator()(const int a,const int b){
        return dis[a]>dis[b];
    }
};

inline void add(int bg,int ed){
    to[++cnt]=ed,nxt[cnt]=head[bg],head[bg]=cnt;
}

inline void add_(int bg,int ed){
    to_[++cnt_]=ed,nxt_[cnt_]=head_[bg],head_[bg]=cnt_;
}

inline bool check(int x){
    for(register int i=head[x];i;i=nxt[i]){
        int u=to[i];
        if(!ar[u]) return false;
    }
    return true;
}

inline void dijkstra(){
    priority_queue<int,vector<int>,cmp> Q;
    memset(dis,0x3f,sizeof(dis));
    Q.push(S);dis[S]=0;if(!check(S)) return;
    while(Q.size()){
        int x=Q.top();Q.pop();
        if(vis[x]) continue;vis[x]=1;
        for(register int i=head[x];i;i=nxt[i]){
            int u=to[i];
            if(dis[x]+1<dis[u])
                if(check(u)){
                    dis[u]=dis[x]+1;
                    Q.push(u);
                }
        }
    }
}

void dfs(int x){
    for(register int i=head_[x];i;i=nxt_[i]){
        int u=to_[i];
        if(vis[u]) continue;
        vis[u]=1;
        ar[u]=1;
        dfs(u);
    }   
}

int main(){
    n=rd(),m=rd();int x,y;
    for(register int i=1;i<=m;i++){
        x=rd(),y=rd();
        add(x,y),add_(y,x);
    }
    S=rd(),T=rd();vis[T]=1,ar[T]=1;dfs(T);
    memset(vis,false,sizeof(vis));
    dijkstra();if(dis[T]!=0x3f3f3f3f) printf("%d",dis[T]);
    else puts("-1");
    return 0;
}
posted @ 2018-08-25 22:11  Monster_Qi  阅读(86)  评论(0编辑  收藏  举报