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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include <bits/stdc++.h> using namespace std; int n, m; const int N = 1e6 + 10; const int M = 1e6 + 10; const int inf = 0x3f3f3f3f; int head[N]; int now[N]; int cnt = 1; struct edge { int u, v, c, val, nxt; edge(int u = 0, int v = 0, int c = 0, int val = 0, int nxt = 0) : u(u), v(v), c(c), val(val), nxt(nxt) {} } e[M]; void ADD(int u, int v, int c, int val) { cnt++; e[cnt] = edge(u, v, c, val, head[u]); head[u] = cnt; } void add_edge(int u, int v, int c, int val) { ADD(u, v, c, val); ADD(v, u, 0, -val); } int d[N]; void add_limit(int u, int v, int l, int r) { add_edge(u, v, r - l, 0); d[u] -= l; d[v] += l; } int s, t; int dep[N]; bool bfs() { memset(dep, 0, sizeof dep); dep[s] = 1; queue<int>q; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); now[u] = head[u]; for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].v; int c = e[i].c; if (dep[v] || !c) continue; dep[v] = dep[u] + 1; q.push(v); } } return dep[t] != 0; } int dfs(int u, int t, int flow) { if (u == t) return flow; int nowflow = 0; for (int i = now[u]; i && nowflow < flow; i = e[i].nxt) { now[u] = i; int v = e[i].v; int c = e[i].c; if (dep[v] != dep[u] + 1 || !c) continue; int ff = dfs(v, t, min(flow - nowflow,c)); if (ff)e[i].c -= ff, e[i ^ 1].c += ff, nowflow += ff; } return nowflow; } int maxflow() { int ans = 0; while (bfs()) { int nowflow; while ((nowflow = dfs(s, t, inf))) ans += nowflow; } return ans; } void work(int n,int m) { memset(head,0,sizeof head); memset(d,0,sizeof d); cnt=1; int tot = 0; int ss, tt; ss = n + m + 1, tt = n + m + 2; s = n + m + 3, t = n + m + 4; for (int i = 1; i <= m; i++) { int g; cin >> g; add_limit(n + i, tt, g, inf); } for (int i = 1; i <= n; i++) { int k, c; cin >> k >> c; add_edge(ss, i, c, 0); for (int j = 1; j <= k; j++) { int t, l, r; cin >> t >> l >> r; t++; add_limit(i, n + t, l, r); } }
for (int i = 1; i <= m + n + 2; i++) { if (d[i] > 0) add_edge(s, i, d[i], 0), tot += d[i]; else add_edge(i, t, -d[i], 0); } add_edge(tt, ss, inf, 0); if (maxflow() != tot) { puts("-1\n"); return; } int ans = e[cnt].c; e[cnt].c = e[cnt ^ 1].c = 0; s = ss, t = tt; ans += maxflow(); cout << ans << endl<<endl; } int main() { while(~scanf("%d%d",&n,&m)) work(n,m); }
|