1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio> #include <string> #include <vector> #include <queue>
#define DEBUG(x) std::cerr << #x << " = " << x << std::endl;
using std::cin; using std::cout; using std::endl;
inline int read() { int s = 0, x = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == '-') x = -x; ch = getchar(); } while (isdigit(ch)) { s = s * 10 + ch - '0'; ch = getchar(); } return s * x; }
const int MAXN = 1000 + 10;
struct Edge { int v, w; Edge(int _v = 0, int _w = 0) : v(_v), w(_w) {} };
int n, ml, md; std::vector<Edge> G[MAXN];
int spfa(int s) { static int dis[MAXN]; memset(dis, 0x3f, sizeof dis); static bool inq[MAXN]; memset(inq, 0, sizeof inq); static int vis[MAXN]; memset(vis, 0, sizeof vis); dis[s] = 0; std::queue<int> q; q.push(s); inq[s] = true; while (!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; ++vis[u]; if (vis[u] > n) return -1; for (int i = 0, siz = (int) G[u].size(); i < siz; ++i) { Edge e = G[u][i]; int v = e.v, w = e.w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; if (!inq[v]) inq[v] = true, q.push(v); } } } return dis[n] == 0x3f3f3f3f ? -2 : dis[n]; }
int main() { n = read(); ml = read(); md = read(); for (int i = 1; i <= ml; ++i) { int a = read(); int b = read(); int d = read(); G[a].push_back(Edge(b, d)); } for (int i = 1; i <= md; ++i) { int a = read(); int b = read(); int d = read(); G[b].push_back(Edge(a, -d)); } for (int i = 2; i <= n; ++i) { G[i].push_back(Edge(i - 1, 0)); } for (int i = 1; i <= n; ++i) { G[0].push_back(Edge(i, 0)); } if (spfa(0) == -1) puts("-1"); else printf("%d\n", spfa(1)); return 0; }
|