【题目链接】
【思路要点】
- 题目中的限制可以总结为“若选取A,则必须选取B”,考虑最大权闭合子图问题。
- 但是我们从样例中发现原图是可能存在环的,而最大权闭合子图问题要求原图是一个有向无环图。
- 进一步分析发现,环上的元素是必然不能选取的,进而连向不能选的元素的元素同样不能选。
- 进行一次DFS,确定每个元素是否可选,在可选的元素中建图,解最大权闭合子图问题即可。
- 时间复杂度\(O(Dinic(N*M,N*M+∑k))\)。
【代码】
#include<bits/stdc++.h> using namespace std; const int MAXN = 55; const int MAXP = 1005; const int INF = 1e9; template <typename T> void read(T &x) { x = 0; int f = 1; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == '-') f = -f; for (; isdigit(c); c = getchar()) x = x * 10 + c - '0'; x *= f; } template <typename T> void write(T x) { if (x < 0) x = -x, putchar('-'); if (x > 9) write(x / 10); putchar(x % 10 + '0'); } template <typename T> void writeln(T x) { write(x); puts(""); } struct edge {int dest, flow; unsigned home; }; int n, m, s, t, tot, flow; int score[MAXP], dist[MAXP]; int point[MAXN][MAXN]; unsigned curr[MAXP]; bool mark[MAXP], vis[MAXP], ins[MAXP]; vector <int> b[MAXP]; vector <edge> a[MAXP]; int dinic(int pos, int limit) { if (pos == t) return limit; int used = 0, tmp; for (unsigned &i = curr[pos]; i < a[pos].size(); i++) { if (a[pos][i].flow && dist[pos] + 1 == dist[a[pos][i].dest] && (tmp = dinic(a[pos][i].dest, min(limit - used, a[pos][i].flow)))) { used += tmp; a[pos][i].flow -= tmp; a[a[pos][i].dest][a[pos][i].home].flow += tmp; } if (used == limit) return used; } return used; } bool bfs() { static int q[MAXP]; static int l = 0, r = -1; for (int i = 0; i <= r; i++) dist[q[i]] = 0; l = 0, r = -1; q[++r] = s; dist[s] = 1; while (l <= r) { int tmp = q[l++]; for (unsigned i = 0; i < a[tmp].size(); i++) if (a[tmp][i].flow && dist[a[tmp][i].dest] == 0) { dist[a[tmp][i].dest] = dist[tmp] + 1; q[++r] = a[tmp][i].dest; } } return dist[t] != 0; } void addedge(int s, int t, int flow) { a[s].push_back((edge) {t, flow, a[t].size()}); a[t].push_back((edge) {s, 0, a[s].size() - 1}); } bool get(int x) { if (vis[x]) return mark[x]; if (ins[x]) return false; ins[x] = true; mark[x] = true; for (unsigned i = 0; i < b[x].size(); i++) mark[x] &= get(b[x][i]); ins[x] = false; vis[x] = true; return mark[x]; } int main() { read(n), read(m); int ans = 0; for (int i = 0; i <= n - 1; i++) for (int j = 0; j <= m - 1; j++) point[i][j] = ++tot; s = 0; t = ++tot; for (int i = 0; i <= n - 1; i++) for (int j = 1; j <= m - 1; j++) b[point[i][j - 1]].push_back(point[i][j]); for (int i = 0; i <= n - 1; i++) for (int j = 0; j <= m - 1; j++) { read(score[point[i][j]]); int cnt; read(cnt); for (int k = 1; k <= cnt; k++) { int x, y; read(x), read(y); b[point[x][y]].push_back(point[i][j]); } } for (int i = 1; i <= tot - 1; i++) { if (!get(i)) continue; if (score[i] >= 0) { ans += score[i]; addedge(s, i, score[i]); } else addedge(i, t, -score[i]); for (unsigned j = 0; j < b[i].size(); j++) if (get(b[i][j])) addedge(i, b[i][j], INF); } while (bfs()) { memset(curr, 0, sizeof(curr)); ans -= dinic(s, INF); } printf("%d\n", ans); return 0; }