Jzoj3934【NOIP2014day2官方数据】寻找道路
先从终点跑一次dijk得到哪几个点是可以连接到终点,让后再跑一次dijk注意不能经过没被标记的点即可
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;
struct node{ int v,id; };
inline bool operator < (node a,node b){ return a.v>b.v; }
inline bool min(int& a,int b){ if(a>b){a=b;return 1;} return 0; }
vector<int> G[10010],G2[10010];
int n,m,d[10010],S,T; bool vis[10010]={0};
void Dijk(int s,vector<int> G[10010]){
memset(d,127,sizeof d);
priority_queue<node> q;
d[s]=0; q.push((node){0,s});
for(node U;!q.empty();){
U=q.top(); q.pop();
if(U.v>d[U.id]||vis[U.id]) continue;
for(int i=0,u=U.id,v,z=G[u].size();i<z;++i)
if(!vis[v=G[u][i]]&&min(d[v],d[u]+1)) q.push((node){d[v],v});
}
}
int main(){
scanf("%d%d",&n,&m);
for(int x,y,i=0;i<m;++i){
scanf("%d%d",&x,&y);
G[x].push_back(y);
G2[y].push_back(x);
}
scanf("%d%d",&S,&T);
Dijk(T,G2);
for(int i=1;i<=n;++i)
if(d[i]==0x7f7f7f7f){
vis[i]=1;
for(int j=0,z=G2[i].size();j<z;++j)
vis[G2[i][j]]=1;
}
Dijk(S,G);
if(d[T]==0x7f7f7f7f) puts("-1");
else printf("%d\n",d[T]);
}