差分约束 SPFA。 如果有环,输出-1,如果N可以无限远,即1与N不连通,输出-2,其他情况输出1与N的最大距离。 按小于等于建图后求最短路即可。 #include <cstdio> #include <cstdlib> #include <iostream> #include <string.h> #include <queue> #include <limits.h> #define MAX 1010 using namespace std; typedef struct COW{ int to,len; COW *next; }COW; COW *cow[MAX],node[MAX*30]; int cou,n; void init() { memset(cow,'/0',sizeof(cow)); memset(node,'/0',sizeof(node)); cou = 0; } void Add(int u,int v,int len) { node[cou].to = v; node[cou].len = len; node[cou].next = cow[u]; cow[u] = &node[cou++]; } int SPFA() { queue<int> q; int i,x,len,to,inq[MAX],dis[MAX],inqtime[MAX]; COW *head; memset(inq,0,sizeof(inq)); memset(inqtime,0,sizeof(inqtime)); for(i=0; i<=n; i++) dis[i] = INT_MAX; q.push(1); dis[1] = 0; inq[1] = inqtime[1] = 1; while( !q.empty() ) { x = q.front(); q.pop(); inq[x] = 0; head = cow[x]; while( head != NULL ) { to = head->to; len = head->len; if( dis[to] > dis[x] + len ) { dis[to] = dis[x] + len; if( !inq[to] ) { inq[to] = 1; q.push(to); inqtime[to]++; if( inqtime[to] > n ) return -1; } } head = head->next; } } if( dis[n] == INT_MAX ) return -2; return dis[n]; } int main() { int ML,MD,from,to,len,i,ans; while( scanf("%d%d%d",&n,&ML,&MD) != EOF ) { init(); while( ML-- ) { scanf("%d%d%d",&from,&to,&len); Add(from,to,len); } while( MD-- ) { scanf("%d%d%d",&from,&to,&len); Add(to,from,-len); } for(i=1; i<=n; i++) Add(i,i-1,0); ans = SPFA(); printf("%d/n",ans); } return 0; }