//差分约束系统 //不等式关系的建立十分直观,eg: //S1和S2之间距离不能大于10 //S2 - S1 <= 10 //S3和S4之间距离不能小于15 //S4 - S3 >= 15 //构图后以1为起点,SPFA求最短路即可 //如果无法到达终点N:If cows 1 and N can be arbitrarily far apart, output -2 //如果存在回路: If no line-up is possible, output -1 #include<iostream> #include<queue> #define INF 1000000000 #define MAXM 20010 #define MAXN 1010 using namespace std; int m,N,ML,MD,u,v,w; int head[MAXN],V[MAXM],W[MAXM],next[MAXM]; int cnt[MAXN],dis[MAXN]; bool inq[MAXN]; void addEdge(int u,int v,int w)//添边 { V[m] = v; W[m] = w; next[m] = head[u]; head[u] = m++; } void buildGraph()//构图 { scanf("%d%d%d",&N,&ML,&MD); memset(head,-1,sizeof(head)); m = 0; while(ML--) { scanf("%d%d%d",&u,&v,&w); addEdge(u,v,w); } while(MD--) { scanf("%d%d%d",&u,&v,&w); addEdge(v,u,-w); } } int SPFA() { memset(cnt,0,sizeof(cnt)); memset(inq,0,sizeof(inq));//是否在队列中 for(int i = 2;i <= N;++i) dis[i] = INF;//初始化 queue<int> q; dis[1] = 0; q.push(1);//1为起点 inq[1] = 1; while(!q.empty()) { int u = q.front(); q.pop(); inq[u] = 0; for(int e = head[u];e != -1;e = next[e]) { if(dis[u] + W[e] < dis[V[e]]) { dis[V[e]] = dis[u] + W[e]; if(!inq[V[e]]) { q.push(V[e]); inq[V[e]] = 1; if(++cnt[V[e]] > N) return -1;//如果入队次数超过N,则存在回路,返回-1 } } } } if(dis[N] == INF) return -2;//不可达,输出-2 else return dis[N];//可达返回到终点的最短距离即为答案 } int main() { //freopen("in.txt","r",stdin); buildGraph(); printf("%d/n",SPFA()); }