nowcoder网络流勤奋的杨老师 最大权闭合子图
Posted kaka0010
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nowcoder网络流勤奋的杨老师 最大权闭合子图相关的知识,希望对你有一定的参考价值。
原题链接:https://ac.nowcoder.com/acm/problem/15828
题意
分析
这题算是最大权闭合子图的模板题了,有不了解的可以先看https://blog.csdn.net/can919/article/details/77603353
二选一问题转化为最小割的模型,然后再根据最大权闭合子图原理,如果选择一个点,那么前驱节点全部都选,因此向前驱节点连无限流量的边。然后再源点连正权点(流量为正权值),负权点连汇点(流量为负权的绝对值)就可以了。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll INF = 1e9;
const int N = 500 + 10;
const int M = 3e6 + 10;
const int MOD = 1e9 + 7;
int st, ed;
struct Maxflow {
int h[N], cnt, maxflow, deep[N], cur[N];
struct Edge {
int to, next;
ll cap;
} e[M<<1];
void init() {
memset(h, -1, sizeof h);
cnt = maxflow = 0;
}
void add(int u, int v, int cap) {
e[cnt].to = v;
e[cnt].cap = cap;
e[cnt].next = h[u];
h[u] = cnt++;
e[cnt].to = u;
e[cnt].cap = 0;
e[cnt].next = h[v];
h[v] = cnt++;
}
bool bfs() {
for (int i = 0; i <= ed; i++) deep[i] = -1, cur[i] = h[i];
queue<int> q; q.push(st); deep[st] = 0;
while (q.size()) {
int u = q.front();
q.pop();
for (int i = h[u]; ~i; i = e[i].next) {
int v = e[i].to;
if (e[i].cap && deep[v] == -1) {
deep[v] = deep[u] + 1;
q.push(v);
}
}
}
if (deep[ed] >= 0) return true;
else return false;
}
ll dfs(int u, ll mx) {
ll a;
if (u == ed) return mx;
for (int i = cur[u]; ~i; i = e[i].next) {
cur[u] = i;//优化
int v = e[i].to;
if (e[i].cap && deep[v] == deep[u] + 1 && (a = dfs(v, min(e[i].cap, mx)))) {
e[i].cap -= a;
e[i ^ 1].cap += a;
return a;
}
}
return 0;
}
void dinic() {
ll res;
while (bfs()) {
while (1) {
res = dfs(st, INF);
if (!res) break;
maxflow += res;
}
}
}
}mf;
int a[N];
void solve() {
int n; cin >> n;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> x >> y;
a[i] = x - y;
}
int u, v;
st = n + 1, ed = n + 2;
mf.init();
while (cin >> u >> v) {
mf.add(v, u, INF);
}
int sum = 0;
for (int i = 1; i <= n; i++) {
if (a[i] <= 0) mf.add(i, ed, -a[i]);
else mf.add(st, i, a[i]), sum += a[i];
}
mf.dinic();
cout << sum - mf.maxflow << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
signed test_index_for_debug = 1;
char acm_local_for_debug = 0;
do {
if (acm_local_for_debug == '$') exit(0);
if (test_index_for_debug > 20)
throw runtime_error("Check the stdin!!!");
auto start_clock_for_debug = clock();
solve();
auto end_clock_for_debug = clock();
cout << "Test " << test_index_for_debug << " successful" << endl;
cerr << "Test " << test_index_for_debug++ << " Run Time: "
<< double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
cout << "--------------------------------------------------" << endl;
} while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
solve();
#endif
return 0;
}
以上是关于nowcoder网络流勤奋的杨老师 最大权闭合子图的主要内容,如果未能解决你的问题,请参考以下文章