/* 这次去查了一下,为什么大家要那样设置INF,有了些新发现 http://blog.csdn.net/jiange_zh/article/details/50198097 以及,这题的思路来自挑战,这个思路真是极其巧妙,将奶牛之间的最短距离、最长距离都转换为了最短路问题 */ #include <iostream> #include <cstdio> const int MAX_ML = 1e4 + 10; const int MAX_MD = 1e4 + 10; const int INF = 0x3f3f3f3f; const int MAX_N = 1010; int N, ML, MD; int AL[MAX_ML], BL[MAX_ML], DL[MAX_ML]; int AD[MAX_MD], BD[MAX_MD], DD[MAX_MD]; int d[MAX_N]; //最短距离 using namespace std; void solve() { fill(d, d + N, INF); d[0] = 0; // 用Bellman-Ford算法计算d for (int k = 0; k < N; k++) { // 从 i+1 到 i 的权值为0 for (int i = 0; i + 1 < N; i++) if (d[i + 1] < INF) d[i] = min(d[i], d[i + 1]); // 从 AL 到 BL 的权值为 DL for (int i = 0; i < ML; i++) { if (d[AL[i] - 1] < INF) d[BL[i] - 1] = min( d[BL[i] - 1], d[AL[i] - 1] + DL[i] ); } // 从 BD 到 AD 的权值为 -DD for (int i = 0; i < MD; i++) { if (d[BD[i] - 1] < INF) d[AD[i] - 1] = min ( d[AD[i] - 1], d[BD[i] - 1] - DD[i] ); } } int res = d[N - 1]; if (d[0] < 0) //存在负圈无解 cout << -1 << endl; else if (res == INF) cout << -2 << endl; else cout << res << endl; } int main() { cin >> N >> ML >> MD; for (int i = 0; i < ML; i++) cin >> AL[i] >> BL[i] >> DL[i]; for (int i = 0; i < MD; i++) cin >> AD[i] >> BD[i] >> DD[i]; solve(); return 0; }