具体讲解看链接,证明的很清楚,神奇的差分约束系统将不等式和图论中的最短路联系起来,数形结合应用的妙不可言。
http://blog.csdn.net/zhang20072844/article/details/7788672
代码如下:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <fstream>
#include <istream>
#include <ostream>
#include <complex>
#include <cstring>
#include <utility>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <string>
#include <cctype>
#include <ctime>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <new>
#include <set>
#include <map>
#define lson l, m, k << 1
#define rson m, r, k << 1 | 1
using namespace std;
typedef long long int LL;
const int INF = 0x3f3f3f3f;
const int maxn = 1005;
int N, ML, MD;
struct edge{
int to, dis;
edge(int a, int b){to = a; dis = b;}
edge(){}
};
vector<edge> G[maxn];
void spfa(){
int Inque[maxn], d[maxn];
memset(Inque, 0, sizeof(Inque));
memset(d, INF, sizeof(d));
queue<int> Q;
Q.push(1);
Inque[1] = 1;
d[1] = 0;
while (!Q.empty()){
int u = Q.front();
Q.pop();
Inque[u] = 0;
for (int i = 0; i < G[u].size(); i++){
edge e = G[u][i];
int v = e.to, w = e.dis;
if (d[v] > d[u] + w){
d[v] = d[u] + w;
if (!Inque[v]){
Q.push(v);
Inque[v] = 1;
}
if (d[v] < 0){
printf("-1\n");
return;
}
}
}
}
if (d[N] == INF) printf("-2\n");
else printf("%d\n", d[N]);
}
int main()
{
//freopen("1.txt", "r", stdin);
scanf("%d%d%d", &N, &ML, &MD);
int u, v, d;//建图
for (int i = 1; i < N; i++)
G[i + 1].push_back(edge(i, 0));
for (int i = 1; i <= ML; i++){
scanf("%d%d%d", &u, &v, &d);
G[u].push_back(edge(v, d));
}
for (int i = 1; i <= MD; i++){
scanf("%d%d%d", &u, &v, &d);
G[v].push_back(edge(u, -d));
}
spfa();
return 0;
}