标签:最大流最小割 graph main ++ 接下来 dep return i++ ==
定义\(图权 = 图中边权总和 ? 图中点权总和\)(空图的图权 =0),求 \(n\) 个点 \(m\) 条边的无向图最大权子图。
第一行为n,m
第二行为点权
接下来为边
输出一行为最大权子图
4 5
1 5 2 2
1 3 4
1 4 4
3 4 5
3 2 2
4 2 2
3 3
9 7 8
1 2 1
2 3 2
1 3 3
8
0
\(1\leq n \leq 10^3, m \leq 10 ^3\)
#include<bits/stdc++.h>
#define LL long long
LL in() {
char ch; LL x = 0, f = 1;
while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
for(x = ch ^ 48; isdigit(ch = getchar()); x = (x << 1) + (x << 3) + (ch ^ 48));
return x * f;
}
const int maxn = 1e4 + 10;
const int inf = 0x7fffffff;
struct node {
int to;
LL dis;
node *nxt, *rev;
node(int to = 0, LL dis = 0, node *nxt = NULL):to(to), dis(dis), nxt(nxt) {}
void *operator new(size_t) {
static node *S = NULL, *T = NULL;
return (S == T) && (T = (S = new node[1024]) + 1024), S++;
}
};
int n, m, s, t;
int dep[maxn];
std::queue<int> q;
node *head[maxn], *cur[maxn];
void add(int from, int to, LL dis) {
head[from] = new node(to, dis, head[from]);
}
void link(int from, int to, int dis) {
add(from, to, dis), add(to, from, 0);
head[from]->rev = head[to];
head[to]->rev = head[from];
}
bool bfs() {
for(int i = s; i <= t; i++) dep[i] = 0, cur[i] = head[i];
q.push(s);
dep[s] = 1;
while(!q.empty()) {
int tp = q.front(); q.pop();
for(node *i = head[tp]; i; i = i->nxt)
if(!dep[i->to] && i->dis)
dep[i->to] = dep[tp] + 1, q.push(i->to);
}
return dep[t];
}
LL dfs(int x, LL change) {
if(x == t || !change) return change;
LL flow = 0, ls;
for(node *i = cur[x]; i; i = i->nxt) {
cur[x] = i;
if(dep[i->to] == dep[x] + 1 && (ls = dfs(i->to, std::min(change, i->dis)))) {
flow += ls;
change -= ls;
i->dis -= ls;
i->rev->dis += ls;
if(!change) break;
}
}
return flow;
}
LL dinic() {
LL flow = 0;
while(bfs()) flow += dfs(s, inf);
return flow;
}
LL ans;
int main() {
n = in(), m = in();
s = 0, t = n + m + 1;
LL x, y, z;
for(int i = 1; i <= n; i++) z = in(), link(m + i, t, z);
for(int i = 1; i <= m; i++) {
x = in(), y = in(), z = in();
link(s, i, z);
link(i, m + x, inf);
link(i, m + y, inf);
ans += z;
}
printf("%lld\n", ans - dinic());
return 0;
}
标签:最大流最小割 graph main ++ 接下来 dep return i++ ==
原文地址:https://www.cnblogs.com/olinr/p/10265034.html