题解
2023-03-31 21:54:00
发布于:上海
18阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
const int Maxn=10005;
const int Maxm=200005;
const int inf=1e9;
int n,m,size,s,t;
int first[Maxn],First[Maxn],v[Maxn],pre[Maxn],dis[Maxn],to[Maxn],vis[Maxn];
struct shu{int to,next;};
shu edge[Maxm<<1],Edge[Maxm<<1];
inline int get_int()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') f=-1,c=getchar();
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline void build(int x,int y)
{
edge[++size].next=first[x];
first[x]=size;
edge[size].to=y;
Edge[size].next=First[y];
First[y]=size;
Edge[size].to=x;
}
inline void dfs(int point)
{
for(int u=First[point];u;u=Edge[u].next)
{
int to=Edge[u].to;
first[to]=0;
}
}
inline void dijkstra()
{
priority_queue<pair<int,int> >q;
for(int i=1;i<=n;i++) dis[i]=inf;
dis[s]=0,q.push(make_pair(0,s));
while(q.size())
{
int point=q.top().second;
q.pop();if(vis[point]) continue;vis[point]=1;
for(int u=first[point];u;u=edge[u].next)
{
int to=edge[u].to;
if(dis[to] > dis[point] + 1)
{
dis[to]=dis[point]+1;
q.push(make_pair(-dis[to],to));
}
}
}
}
int main()
{
n=get_int(),m=get_int();
for(int i=1;i<=m;i++)
{
int x=get_int(),y=get_int();
build(x,y),to[x]++;
}
s=get_int(),t=get_int();
for(int i=1;i<=n;i++) if(!to[i] && i!=t) dfs(i);
dijkstra();
if(dis[t]==inf) cout<<"-1\n";
else cout<<dis[t]<<"\n";
return 0;
}
这里空空如也
有帮助,赞一个