思路:差分约束SPFA。必须用栈
#include <stdio.h> #include <string.h> #define N 30005 #define M 150005 #define INF 0x3fffffff struct edge{ int y,w,next; }e[M]; int first[N],dis[N],visited[N]; int stack[N]; int n,m,top,tops; void init(){ int i; top = 0; tops = -1; memset(first,-1,sizeof(first)); memset(visited,0,sizeof(visited)); for(i = 1;i<=n;i++) dis[i] = INF; } void add(int x,int y,int w){ e[top].y = y; e[top].w = w; e[top].next = first[x]; first[x] = top++; } int relax(int x,int y,int w){ if(dis[x]+w < dis[y]){ dis[y] = dis[x]+w; return 1; } return 0; } int spfa(int s,int t){ int i,j; visited[s] = 1; dis[s] = 0; stack[++tops] = s; while(tops > -1){ int now = stack[tops--]; visited[now] = 0; for(i = first[now];i!=-1;i=e[i].next){ j = e[i].y; if(relax(now,j,e[i].w) && !visited[j]){//这地方把now写成了i,故wa了若干次 stack[++tops] = j; visited[j] = 1; } } } return dis[t]; } int main(){ freopen("a.txt","r",stdin); while(scanf("%d %d",&n,&m)!=EOF){ int a,b,w; init(); while(m--){ scanf("%d %d %d",&a,&b,&w); add(a,b,w); } printf("%d\n",spfa(1,n)); } return 0; }