CF1082G Petya and Graph

(color{#0066ff}{ 题目描述 })

定义(图权 = 图中边权总和 − 图中点权总和)(空图的图权 =0),求 (n) 个点 (m) 条边的无向图最大权子图。

(color{#0066ff}{输入格式})

第一行为n,m

第二行为点权

接下来为边

(color{#0066ff}{输出格式})

输出一行为最大权子图

(color{#0066ff}{输入样例})

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

(color{#0066ff}{输出样例})

8
    
   
0

(color{#0066ff}{数据范围与提示})

(1leq n leq 10^3, m leq 10 ^3)

(color{#0066ff}{ 题解 })

最大流最小割定理

S向所有边建容量为边权的边

所有点向T建容量为点权的边

每条边向对应的两个点建容量为inf的边

(ans=sum 边权-最大流(最小割))

#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
", ans - dinic());
	return 0;
}
原文地址:https://www.cnblogs.com/olinr/p/10265034.html