链接
题意:给定一张图,有左侧的点和右侧的点,左侧的点点权为正(对应试验),右侧的点点权为负(对应器材),如果选择了左侧的某个点就必须要选右边的一部分点。要求最大化点权和。
如果一个点被选择了则后继必须被选择,那么称该图是 闭合的,因此该问题叫做最大权闭合子图问题。
最
大
权
闭
合
子
图
的
权
值
和
=
正
点
权
和
−
最
小
割
最大权闭合子图的权值和 =正点权和−最小割
最大权闭合子图的权值和=正点权和−最小割
打印图利用d数组的值来判断
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 550;
const int maxm = maxn * 50;
int n, m;
int to[maxm], nxt[maxm], w[maxm];
int fst[maxn], cnt, cur[maxn];
int s, t, d[maxn];
void init() {
memset(fst, -1, sizeof(fst));
cnt = 0;
}
void addedge(int u, int v, int val) {
to[cnt] = v;
w[cnt] = val;
nxt[cnt] = fst[u];
fst[u] = cnt++;
to[cnt] = u;
w[cnt] = 0;
nxt[cnt] = fst[v];
fst[v] = cnt++;
}
int bfs() {
queue<int> Q;
memset(d, 0, sizeof(d));
d[s] = 1;
Q.push(s);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
for (int i = fst[u]; ~i; i = nxt[i]) {//因为初始是-1
int v = to[i];
if (w[i] > 0 && d[v] == 0) {
d[v] = d[u] + 1;
if (v == t) return 1;
Q.push(v);
}
}
}
return d[t] != 0;
}
int dfs(int u, int flow) {
if (u == t)
return flow;
int ans = 0, x = 0;
for (int i = cur[u]; ~i; i = nxt[i]) {
int v = to[i];
if (w[i] > 0 && d[v] == d[u] + 1) {
x = dfs(v, min(flow - ans, w[i]));
w[i] -= x;
w[i ^ 1] += x;
if (w[i]) cur[u] = i;
ans += x;
if (ans == flow) return flow;
}
}
if (ans == 0)d[u] = 0;
return ans;
}
int dinic(int n) {
int ans = 0;
while (bfs()) {
for (int i = 0; i < n; i++)
cur[i] = fst[i];
ans += dfs(s, INF);
}
return ans;
}
int main() {
// ios::sync_with_stdio(false);
// cin.tie(0);
// cout.tie(0);
cin >> m >> n;
init();
s = 0;
t = m + n + 1;
int sum = 0;
for (int i = 1; i <= m; i++) {
int x;
char ch;
scanf("%d", &x);
addedge(s, i, x);
sum += x;
while (1) {
scanf("%d%c", &x, &ch);
addedge(i, x + m, INF);
if (ch == '\n' || ch == '\r') break;
}
}
for (int i = 1; i <= n; i++) {
int x;
scanf("%d", &x);
addedge(m + i, t, x);
}
sum -= dinic(t);
for (int i = 1; i <= m; i++)
if (d[i]) printf("%d ", i);
cout << endl;
for (int i = 1; i <= n; i++)
if (d[i + m]) printf("%d ", i);
cout << endl;
cout << sum << endl;
}