ACdream1171 下界轉上界-最大費用可行流

每一行/列至少取A/B的最小費用=SUM-每一行/列至多取m-A/n-B的最大費用

由於是求可行流而不是最大流,所以添加超級源匯,在源匯上連一條分流的路

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
#define ll __int64

int n,m;

const int N = 110;//點
const int M = 2 * 3000;//邊
const int inf = 1000000000;
struct Node{//邊,點f到點t,流量爲c,費用爲w
	int f, t, c, w;
}e[M];
int next1[M], point[N], dis[N], q[N], pre[N], ne;//ne爲已添加的邊數,next,point爲鄰接表,dis爲花費,pre爲父親節點
bool u[N];
void init(){
	memset(point, -1, sizeof(point));
	ne = 0;
}
void add_edge(int f, int t, int d1, int d2, int w){//f到t的一條邊,流量爲d1,反向流量d2,花費w,反向邊花費-w(可以反悔)
	e[ne].f = f, e[ne].t = t, e[ne].c = d1, e[ne].w = w;
	next1[ne] = point[f], point[f] = ne++;
	e[ne].f = t, e[ne].t = f, e[ne].c = d2, e[ne].w = -w;
	next1[ne] = point[t], point[t] = ne++;
}
bool spfa(int s, int t, int n){
	int i, tmp, l, r;
	memset(pre, -1, sizeof(pre));
	for(i = 0; i < n; ++i)
		dis[i] = inf;
	dis[s] = 0;
	q[0] = s;
	l = 0, r = 1;
	u[s] = true;
	while(l != r) {
		tmp = q[l];
		l = (l + 1) % (n + 1);
		u[tmp] = false;
		for(i = point[tmp]; i != -1; i = next1[i]) {
			if(e[i].c && dis[e[i].t] > dis[tmp] + e[i].w) {
				dis[e[i].t] = dis[tmp] + e[i].w;
				pre[e[i].t] = i;
				if(!u[e[i].t]) {
					u[e[i].t] = true;
					q[r] = e[i].t;
					r = (r + 1) % (n + 1);
				}
			}
		}
	}
	if(pre[t] == -1)
		return false;
	return true;
}
void MCMF(int s, int t, int n, int &flow, int &cost){//起點s,終點t,點數n,最大流flow,最小花費cost
	int tmp, arg;
	flow = cost = 0;
	while(spfa(s, t, n)) {
		arg = inf, tmp = t;
		while(tmp != s) {
			arg = min(arg, e[pre[tmp]].c);
			tmp = e[pre[tmp]].f;
		}
		tmp = t;
		while(tmp != s) {
			e[pre[tmp]].c -= arg;
			e[pre[tmp] ^ 1].c += arg;
			tmp = e[pre[tmp]].f;
		}
		flow += arg;
		cost += arg * dis[t];
	}
}
//建圖前運行init()
//節點下標從0開始
//加邊時運行add_edge(a,b,c,0,d)表示加一條a到b的流量爲c花費爲d的邊(注意花費爲單位流量花費)
//特別注意雙向邊,運行add_edge(a,b,c,0,d),add_edge(b,a,c,0,d)較好,不要只運行一次add_edge(a,b,c,c,d),費用會不對。
//求解時代入MCMF(s,t,n,v1,v2),表示起點爲s,終點爲t,點數爲n的圖中,最大流爲v1,最大花費爲v2

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		init();
		int i,j;
		int ta,tb,tc;
		int sum=0;
		scanf("%d%d",&n,&m);
		for(i=1;i<=n;i++)
			for(j=1;j<=m;j++)
			{
				scanf("%d",&ta);
				sum+=ta;
				add_edge(i,n+j,1,0,-ta);
			}
		for(i=1;i<=n;i++)
		{
			scanf("%d",&ta);
			add_edge(0,i,m-ta,0,0);
		}
		for(j=1;j<=m;j++)
		{
			scanf("%d",&ta);
			add_edge(n+j,n+m+1,n-ta,0,0);
		}
		add_edge(0,n+m+1,n*m,0,0);
		add_edge(n+m+2,0,n*m,0,0);
		add_edge(n+m+1,n+m+3,n*m,0,0);
		int fl,ans;
		MCMF(n+m+2,n+m+3,n+m+4,fl,ans);
		printf("%d\n",sum+ans);
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章