这道题和种树差不多,但是n和m数字较大,所以加上了SLF LLL优化,但是最后一个点还是不过,还加了个CLOCK(不知道还有没有更好的方法
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+5;
int cnt,tot,n,m,update[maxn],dis[maxn],vis[maxn],head[maxn];
struct edge
{
int to,v,nxt;
}G[maxn<<2];
clock_t start;
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)
{
long long sum=0;
memset(dis,0x3f,sizeof(dis));
dis[s]=0; vis[s]=1;
q.push_back(s); tot++;
while(!q.empty())
{
int u=q.front();
q.pop_front();
tot--; sum-=dis[u];
if(tot && dis[u]*tot>sum)
{
q.push_back(u);
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;
tot++;
sum+=dis[to];
}
if(update[to]>=n || clock()-start>=0.7*CLOCKS_PER_SEC) return true;
}
}
}
return false;
}
int main()
{
freopen("P3084_10.in","r",stdin);
freopen("a.out","w",stdout);
start=clock();
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;
}