NOI 2006 最大获利 (最大权闭合子图)

点击打开链接

比较模版的最大权闭合子图。

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
const int maxn = 55005;
const int maxm = 1e6;
const int INF = 0x3f3f3f3f;
using namespace std;
inline int read()
{
	int x=0,t=1,c;
	while(!isdigit(c=getchar()))if(c=='-')t=-1;
	while(isdigit(c))x=x*10+c-'0',c=getchar();
	return x*t;
}
int head[maxn],cur[maxn],nx[maxm<<1],to[maxm<<1],flow[maxm<<1],ppp=0;
struct Dinic
{
	int dis[maxn];
	int s, t;
	long long ans;
	
	void init() {
		memset(head, -1, sizeof(head));
		ppp = 0;
	}
	
	void AddEdge(int u, int v, int c)
	{
		to[ppp]=v;flow[ppp]=c;nx[ppp]=head[u];head[u]=ppp++;swap(u,v);
		to[ppp]=v;flow[ppp]=0;nx[ppp]=head[u];head[u]=ppp++;
	}
	
	bool BFS()
	{
		memset(dis, -1, sizeof(dis));
		dis[s] = 1; 
		queue<int> Q;
		Q.push(s);
		while(!Q.empty())
		{
			int x = Q.front();
			Q.pop();
			for(int i = head[x]; ~i; i = nx[i])
			{
				if(flow[i] && dis[to[i]] == -1)
				{
					dis[to[i]] = dis[x] + 1;
					Q.push(to[i]);
				}
			}
		}
		return dis[t] != -1;
	}
	
	int DFS(int x, int maxflow)
	{
		if(x == t || !maxflow){
			ans += maxflow;
			return maxflow;
		}
		int ret = 0, f;
		for(int &i = cur[x]; ~i; i = nx[i])
		{
			if(dis[to[i]] == dis[x] + 1 && (f = DFS(to[i], min(maxflow, flow[i]))))
			{
				ret += f;
				flow[i] -= f;
				flow[i^1] += f;
				maxflow -= f;
				if(!maxflow)
					break;
			}
		}
		return ret;
	}
	
	long long solve(int source, int tank)
	{
		s = source;
		t = tank;
		ans = 0;
		while(BFS())
		{
			memcpy(cur, head, sizeof(cur));
			DFS(s, INF);
		}
		return ans;
	}
}dinic;

int main()
{
	int n = read(), m = read();
	int s = 0, t = n + m + 1;
	dinic.init();
	for(int i = 1, p; i <= n; i++) {
		scanf("%d", &p);
		dinic.AddEdge(m + i, t, p);
	}
	long long cnt = 0;
	for(int i = 1; i <= m; i++) {
		int v1 = read(), v2 = read(), c = read();
		cnt += c;
		dinic.AddEdge(s, i, c);
		dinic.AddEdge(i, m + v1, INF);
		dinic.AddEdge(i, m + v2, INF);
	}
	printf("%lld\n", cnt - dinic.solve(s,t));
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值