这道题和种树差不多,但是n和m数字较大,所以加上了SLF优化,但是最后一个点还是不过,待修改!
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;
int cnt,n,m,update[maxn],dis[maxn],vis[maxn],head[maxn];
struct edge
{int to,v,nxt;
}G[maxn<<2];
void add(int x,int y, int z)
{G[++cnt].to=y; G[cnt].nxt=head[x]; G[cnt].v=z; head[x]=cnt;
}
deque <int> q;
bool spfa(int s)
{memset(dis,0x3f,sizeof(dis));dis[s]=0; vis[s]=1;q.push_back(s);while(!q.empty()){int u=q.front();q.pop_front(); vis[u]=0;for(int i=head[u];i;i=G[i].nxt){int to=G[i].to;int v=G[i].v;if(dis[to]>dis[u]+v){dis[to]=dis[u]+v;if(!vis[to]){update[to]=update[u]+1; if(q.size() && dis[q.front()]<dis[to]) q.push_back(to);else q.push_front(to);vis[to]=1;}if(update[to]>=n) return true;}}}return false;
}
int main()
{freopen("P3084_10.in","r",stdin);freopen("a.out","w",stdout);int x,y;scanf("%d%d",&n,&m);for(int i=1;i<=m;i++){scanf("%d%d",&x,&y);add(x-1,y,1);add(y,x-1,-1);}for(int i=1;i<=n;i++) add(i,i-1,0),add(i-1,i,1);if(spfa(0)) printf("%d\n",-1);else printf("%d\n",dis[n]);return 0;
}