先反向跑一边bfs,然后将到达不了的点以及它的邻接点删掉。(注意只删一层)
然后再正向跑一遍bfs就可以了。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<queue>
using namespace std;
const int N=10009;
const int M=200009;
int head[N],nxt[M],to[M],tot;
int head2[N],nxt2[M],to2[M],tot2;
int n,m,s,t,ans;
bool used[N],vis[N];
struct H{
int x,step;
};
void add(int x,int y)
{
to[++tot]=y;
nxt[tot]=head[x];
head[x]=tot;
}
void add2(int x,int y)
{
to2[++tot2]=y;
nxt2[tot2]=head2[x];
head2[x]=tot2;
}
void color()
{
queue <int> q;
q.push(t);
used[t]=1;
while(!q.empty())
{
int k=q.front();q.pop();
for(int i=head2[k];i;i=nxt2[i])
{
if(!used[to2[i]])
{
used[to2[i]]=1;
q.push(to2[i]);
}
}
}
for(int x=1;x<=n;x++)
if(!used[x])
{
for(int i=head2[x];i;i=nxt2[i])
{
//used[to2[i]]=0;一定不是这样!!!我就是因为这个错误WA了8个点
vis[to2[i]]=1;
}
}
}
int bfs()
{
queue <H> q;
q.push((H){s,0});
vis[s]=1;
while(!q.empty())
{
H k=q.front();q.pop();
if(k.x==t) return k.step;
for(int i=head[k.x];i;i=nxt[i])
{
if(used[to[i]]&&!vis[to[i]])
vis[to[i]]=1,q.push((H){to[i],k.step+1});
}
}
return -1;
}
int main()
{
//freopen("road.in","r",stdin);
//freopen("road.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
add(x,y);add2(y,x);
}
scanf("%d%d",&s,&t);
color();
ans=bfs();
printf("%d\n",ans);
//printf("%d",clock());
return 0;
}