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
| #include <bits/stdc++.h> using namespace std; typedef long long ll;
const ll INF = 1e9; const int MAXN = 605; const int MAXM = 605 * 305;
int n, m, s, t;
struct Edge { int v, nxt; ll w; } edge[MAXM << 1]; int head[MAXN], cnt = 1; int head_or[MAXN];
void AddEdge(int u, int v, ll w) { edge[++cnt].w = w; edge[cnt].v = v; edge[cnt].nxt = head[u]; head[u] = cnt; }
int d[MAXN]; bool vis[MAXN];
bool bfs() { memset(vis, 0, sizeof(vis)); memcpy(head, head_or, sizeof(head)); vis[s] = 1, d[s] = 0; queue<int> q; q.push(s); while (q.size()) { int u = q.front(); q.pop(); for (int i = head[u]; i; i = edge[i].nxt) { int v = edge[i].v; ll w = edge[i].w; if (vis[v] || (w == 0)) continue; vis[v] = 1; d[v] = d[u] + 1; q.push(v); } } return vis[t]; }
ll dfs(int u, ll flow) { if (u == t) return flow; ll rest = flow; for (int i = head[u]; i && rest; i = edge[i].nxt) { head[u] = i; int v = edge[i].v; ll w = edge[i].w; if (w == 0 || d[v] != d[u] + 1) continue; ll tmp = dfs(v, min(rest, w)); if (tmp == 0) d[v] = 0; edge[i].w -= tmp; edge[i ^ 1].w += tmp; rest -= tmp; } return flow - rest; }
ll dinic() { ll ret = 0, tmp = 0; while (bfs()) while (tmp = dfs(s, INF)) ret += tmp; return ret; }
int main() { scanf("%d", &n); s = 2 * n + 1, t = 2 * n + 2; for (int i = 1; i <= n; ++i) { int k = 0; scanf("%d", &k); for (int j = 1; j <= k; ++j) { int x; scanf("%d", &x); AddEdge(i, n + x, INF); AddEdge(n + x, i, 0); } } ll ans2 = 0; for (int i = 1; i <= n; ++i) { int p; scanf("%d", &p); ans2 += INF - p; AddEdge(s, i, INF - p); AddEdge(i, s, 0); AddEdge(n + i, t, INF); AddEdge(t, n + i, 0); } memcpy(head_or, head, sizeof(head_or)); ll ans = dinic(); cout << ans - ans2 << endl;
return 0; }
|