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
| #include <bits/stdc++.h> using namespace std;
typedef long long ll; const int N = 3005, M = 1e7 + 5, inf = 1 << 30; int n, m, s, t, dis[N], head[N], cnt = 1, tot, now[N]; struct E { int nxt, v, w; } e[M];
void add(int u, int v, int w) { e[++cnt] = {head[u], v, w}; head[u] = cnt; e[++cnt] = {head[v], u, 0}; head[v] = cnt; }
bool bfs() { queue<int> q; for (int i = 1; i <= tot; i++) dis[i] = inf; dis[s] = 0; now[s] = head[s]; q.push(s); while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].v; if (dis[v] == inf && e[i].w > 0) { dis[v] = dis[u] + 1; now[v] = head[v]; q.push(v); if (v == t) return 1; } } } return 0; } int dfs(int u, int sum) { if (u == t) return sum; int k, res = 0; for (int i = now[u]; i && sum; i = e[i].nxt) { now[u] = i; int v = e[i].v; if (dis[v] == dis[u] + 1 && e[i].w > 0) { k = dfs(v, min(sum, e[i].w)); if (k == 0) dis[v] = inf; e[i].w -= k; e[i ^ 1].w += k; sum -= k; res += k; } } return res; } ll dinic(int s, int t) { ll res = 0; while (bfs()) res += dfs(s, inf); return res; }
int main() { ll res = 0; scanf("%d", &n); tot = n; s = ++tot, t = ++tot; for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); add(s, i, x); res += x; } for (int i = 1; i <= n; i++) { int x; scanf("%d", &x); add(i, t, x); res += x; } scanf("%d", &m); for (int i = 1; i <= m; i++) { int z, x, y, ss = ++tot, tt = ++tot; scanf("%d", &z); scanf("%d %d", &x, &y); add(s, ss, x); add(tt, t, y); res += x + y; for (int j = 1; j <= z; j++) { scanf("%d", &y); add(ss, y, inf); add(y, tt, inf); } } printf("%lld\n", res - dinic(s, t)); return 0; }
|