实际上也是水题。。首先从终点沿反向边将所有能到达终点的点求出来。然后枚举每个点看是否符合题目中的第一条条件。然后沿着所有满足条件的点找出最短路就行了。
把一个sta达成1WA了一发。。真是没救了:
#include<iostream>
#include<cstdio>
#include<cstring>
#define N 400005
using namespace std;
int n,m,sta,gol,tot,fst[N],pnt[N],nxt[N],len[N];
int d[N],h[N]; bool vis[N],ok[N];
void add(int aa,int bb,int cc){
pnt[++tot]=bb; len[tot]=cc; nxt[tot]=fst[aa]; fst[aa]=tot;
}
int main(){
scanf("%d%d",&n,&m); int i;
for (i=1; i<=m; i++){
int x,y; scanf("%d%d",&x,&y);
add(x,y,1); add(y,x,0);
}
scanf("%d%d",&sta,&gol);
int head=0,tail=1; vis[gol]=1; h[1]=gol;
while (head<tail){
int x=h[++head],p;
for (p=fst[x]; p; p=nxt[p]) if (!len[p]){
int y=pnt[p];
if (!vis[y]){ vis[y]=1; h[++tail]=y; }
}
}
for (i=1; i<=n; i++){
ok[i]=1; int p;
for (p=fst[i]; p; p=nxt[p])
if (len[p] && !vis[pnt[p]]){ ok[i]=0; break; }
}
memset(d,-1,sizeof(d)); d[sta]=0;
head=0; tail=1; h[1]=sta;
while (head<tail){
int x=h[++head],p;
for (p=fst[x]; p; p=nxt[p]) if (len[p]){
int y=pnt[p]; if (!ok[y]) continue;
if (d[y]==-1){
d[y]=d[x]+1; h[++tail]=y;
}
}
}
printf("%d\n",d[gol]);
return 0;
}
by lych
2015.12.22