题面
解法
经典的最小割问题
- 要解决这个问题,不妨先考虑一下如果没有组合的情况怎么求解
- 显然,就直接把 S S 连向每一个点,容量为,每一个点连向 T T ,容量为,最后的总价值显然就是 (∑ai+bi)−maxflow ( ∑ a i + b i ) − m a x f l o w ,即最小割
- 那么,我们再考虑一下如果有组合怎么做
- 可以对于每一组构建出两个点 x′,y′ x ′ , y ′ , x′ x ′ 表示这些点全在 S S 集,表示这些点全在 T T 集
- 考虑如何建边,可以把连向所有组合里的点,所有组合里的点连向 y′ y ′ , S S 连向, y′ y ′ 连向 T T ,容量分别为
- 但是,我们需要考虑,如果某一个点 x x 被割入了集中,那么它到 S S 的路径必须被断开,它所在的组合就不应该被计算进入答案中。那么我们可以将每一个组合中的和组合里所有点的连边容量均设为 ∞ ∞ ,这样就可以保证这条边一定不可能被计算入最小割中,那么割掉的就是 S S 到这个点的连边了
- 最后,我们只要用总价值-最小割即可
- 用 dinic d i n i c 算法实现这个过程,建议使用当前弧优化
代码
#include <bits/stdc++.h>
#define N 3010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
int next, num, c;
} e[N * N];
int s, t, cnt, a[N], b[N], l[N], cur[N];
void add(int x, int y, int c) {
e[++cnt] = (Edge) {e[x].next, y, c};
e[x].next = cnt;
}
void Add(int x, int y, int c) {
add(x, y, c), add(y, x, 0);
}
bool bfs(int s) {
for (int i = 1; i <= t; i++) l[i] = -1;
queue <int> q; q.push(s);
while (!q.empty()) {
int x = q.front(); q.pop();
for (int p = e[x].next; p; p = e[p].next) {
int k = e[p].num, c = e[p].c;
if (c && l[k] == -1)
q.push(k), l[k] = l[x] + 1;
}
}
return l[t] != -1;
}
int dfs(int x, int lim) {
if (x == t) return lim;
int used = 0;
for (int p = cur[x]; p; p = e[p].next) {
int k = e[p].num, c = e[p].c;
if (l[k] == l[x] + 1 && c) {
int w = dfs(k, min(c, lim - used));
e[p].c -= w, e[p ^ 1].c += w, used += w;
if (e[p].c) cur[x] = p;
if (used == lim) return lim;
}
}
if (!used) l[x] = -1; return used;
}
int dinic() {
int ret = 0;
while (bfs(s)) {
for (int i = 0; i <= t; i++) cur[i] = e[i].next;
ret += dfs(s, INT_MAX);
}
return ret;
}
int main() {
int n; read(n);
for (int i = 1; i <= n; i++) read(a[i]);
for (int i = 1; i <= n; i++) read(b[i]);
int m; read(m); s = 0, t = cnt = n + 2 * m + 1;
if (cnt % 2 == 0) cnt++; int ans = 0;
for (int i = 1; i <= n; i++)
Add(s, i, a[i]), Add(i, t, b[i]), ans += a[i] + b[i];
for (int i = 1; i <= m; i++) {
int k, tx, ty; read(k), read(tx), read(ty);
ans += tx + ty; int x1 = n + i * 2 - 1, x2 = x1 + 1;
Add(s, x1, tx), Add(x2, t, ty);
while (k--) {
int x; read(x);
Add(x1, x, INT_MAX), Add(x, x2, INT_MAX);
}
}
cout << ans - dinic() << "\n";
return 0;
}