[NOIP2014]寻找道路----简单bfs
作者:互联网
题目链接
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N = 200010;
int n,m;
int h[N],e[N],ne[N],idx=0;
int st,ed;
int dis[N];
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int bfs(int st,int ed){
memset(dis,-1,sizeof dis);
queue<int>q;
q.push(st);
dis[st]=0;
while(q.size())
{
int t=q.front();
q.pop();
bool flag=true;
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(h[j]==-1&&j!=ed)
{
flag=false;
break;
}
}
if(flag)
{
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(dis[j]!=-1)continue;
dis[j]=dis[t]+1;
if(j==ed)return dis[t]+1;
q.push(j);
}
}
}
return dis[ed];
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
for(int i=1;i<=m;i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
cin>>st>>ed;
cout<<bfs(st,ed)<<endl;
}
标签:----,NOIP2014,int,ed,ne,st,bfs,include,dis 来源: https://blog.csdn.net/qq_51282224/article/details/122391339