【网络流】 HDOJ 3879 Base Station

最大权闭合图。。。简单题

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int maxn = 60005;
const int maxm = 400005;
const int INF = 0x3f3f3f3f;

struct Edge
{
	int v, c, next;
	Edge() {}
	Edge(int v, int c, int next) : v(v), c(c), next(next) {}
}E[maxm];

queue<int> q;
int H[maxn], cntE;
int dis[maxn];
int cur[maxn];
int cnt[maxn];
int pre[maxn];
int n, m, s, t, flow, nv;

void addedges(int u, int v, int c)
{
	E[cntE] = Edge(v, c, H[u]);
	H[u] = cntE++;
	E[cntE] = Edge(u, 0, H[v]);
	H[v] = cntE++;
}

void bfs()
{
	memset(cnt, 0, sizeof cnt);
	memset(dis, -1, sizeof dis);
	cnt[0]++, dis[t] = 0;
	q.push(t);
	while(!q.empty()) {
		int u = q.front();
		q.pop();
		for(int e = H[u]; ~e; e = E[e].next) {
			int v = E[e].v;
			if(dis[v] == -1) {
				dis[v] = dis[u] + 1;
				cnt[dis[v]]++;
				q.push(v);
			}
		}
	}
}

int isap()
{
	memcpy(cur, H, sizeof cur);
	bfs();
	flow = 0;
	int u = pre[s] = s, f, minv, e, pos;
	while(dis[s] < nv) {
		if(u == t) {
			f = INF;
			for(int i = s; i != t; i = E[cur[i]].v) if(f > E[cur[i]].c) {
				f = E[cur[i]].c;
				pos = i;
			}
			for(int i = s; i != t; i = E[cur[i]].v) {
				E[cur[i]].c -= f;
				E[cur[i] ^ 1].c += f;
			}
			flow += f;
			u = pos;
		}
		for(e = cur[u]; ~e; e = E[e].next) if(E[e].c && dis[E[e].v] + 1 == dis[u]) break;
		if(~e) {
			cur[u] = e;
			pre[E[e].v] = u;
			u = E[e].v;
		}
		else {
			if(--cnt[dis[u]] == 0) break;
			for(minv = nv, e = H[u]; ~e; e = E[e].next) if(E[e].c && minv > dis[E[e].v]) {
				minv = dis[E[e].v];
				cur[u] = e;
			}
			dis[u] = minv + 1;
			cnt[dis[u]]++;
			u = pre[u];
		}
	}
	return flow;
}

void init()
{
	cntE = 0;
	memset(H, -1, sizeof H);
}

void work()
{
	int a, b, c, sum = 0, x;
	s = 0, t = n + m + 1, nv = t + 1;
	for(int i = 1; i <= n; i++) {
		scanf("%d", &x);
		addedges(i, t, x);
	}
	for(int i = 1; i <= m; i++) {
		scanf("%d%d%d", &a, &b, &c);
		addedges(s, i + n, c);
		addedges(i + n, a, INF);
		addedges(i + n, b, INF);
		sum += c;
	}
	printf("%d\n", sum - isap());
}

int main()
{
	while(scanf("%d%d", &n, &m) != EOF) {	
		init();
		work();
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值