https://www.luogu.org/blog/FakeSilhouette/solution-p3084
虽然是道dp但是学到了暴力spfa+1sspfa黑框spfa膜蛤spfa梦想spfa
双端队列spfa,那个质数判负环
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #define pb push_back #define pf push_front #define ppf pop_front #define ppb pop_back using namespace std; const int maxn=1000009; const int inf=1e9+7; struct node{ int v,w,nxt; }e[maxn*3]; int head[maxn],d[maxn],vis[maxn],cnt,n,mn,mx,m; void add(int u,int v,int w){ e[++cnt].v=v; e[cnt].nxt=head[u]; e[cnt].w=w; head[u]=cnt; } int cntt[maxn];int tot=0; int spfa(){ memset(d,0x3f,sizeof(d)); deque<int>q; q.push_back(0);d[0]=0;vis[0]=1; while(!q.empty()){ int x=q.front();q.pop_front();vis[x]=0; for(int i=head[x];i;i=e[i].nxt){ int y=e[i].v; if(d[y]>d[x]+e[i].w){ d[y]=d[x]+e[i].w; // cntt[y]=cntt[x]+1; if(!vis[y]){ vis[y]=1; // if(cntt[y]>n)return -1; if(++tot>1926817*5)return -1;//大点约785ms if(!q.empty()&&d[y]>d[q.front()])q.push_back(y); else q.push_front(y); } } } } return d[n]; } int main(){ scanf("%d%d",&n,&m); for(int i=0,u,v;i<m;i++){ scanf("%d%d",&u,&v); add(u-1,v,1); add(v,u-1,-1); } for(int i=1;i<=n;i++){ add(i-1,i,1);add(i,i-1,0); } printf("%d",spfa()); }