运输问题(费用流)

//http://www.cnblogs.com/IMGavin/
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <bitset>
#include <algorithm>
using namespace std;

typedef long long LL;
#define gets(A) fgets(A, 1e8, stdin)

const int N = 1008, M = 50000, INF=0x3F3F3F3F;//注意INF
struct Node{
	int u, v, cap, cost;
	int next;
}edge[M];//有向图,u到v的容量,费用
int tot;
int head[N], pre[N], path[N], dis[N];
bool inq[N];

int a[N], b[N], c[N][N];

void init(){
	tot = 0;
	memset(head, -1, sizeof(head));
}

void add(int u, int v, int cap, int cost){
	edge[tot].u = u;
	edge[tot].v = v;
	edge[tot].cap = cap;
	edge[tot].cost = cost;
	edge[tot].next = head[u];
	head[u] = tot++;
	edge[tot].u = v;
	edge[tot].v = u;
	edge[tot].cap = 0;
	edge[tot].cost = -cost;
	edge[tot].next = head[v];
	head[v] = tot++;
}

bool SPFA(int st, int des){//计算最小费用
	memset(inq, 0, sizeof(inq));
	memset(dis, 0x3f, sizeof(dis));
	queue <int> q;
	q.push(st);
	dis[st] = 0;
	inq[st] = true;
	while(!q.empty()){
		int u = q.front();
		q.pop();
		inq[u] = false;
		for(int i = head[u]; ~i; i = edge[i].next){
			int v = edge[i].v;
			if(edge[i].cap > 0 && dis[v] > dis[u] + edge[i].cost){
				dis[v] = dis[u] + edge[i].cost;
				pre[v] = u;
				path[v] = i;
				if(!inq[v]){
					inq[v] = true;
					q.push(v);
				}
			}
		}
	}
	return dis[des] < INF;
}

int EdmondsKarp(int st, int des){//最小费用最大流
	int mincost = 0, flow = 0;//最小费用与流量
	while(SPFA(st, des)){
		int f = INF;
		for(int i = des; i != st; i = pre[i]){
            if(f > edge[path[i]].cap){
                f = edge[path[i]].cap;
            }
		}
		for(int i = des; i != st; i = pre[i]){
			edge[path[i]].cap -= f;
			edge[path[i]^1].cap += f;
		}
		mincost += f * dis[des];
		flow += f;
	}
	return mincost;
}

int m, n;

int solve(bool mx){
	init();
	int st = 0, des = m + n + 1;
	for(int i = 1; i <= m; i++){
		add(st, i, a[i], 0);
	}

	for(int i = 1; i <= n; i++){
		add(i + m, des, b[i], 0);
	}

	for(int i = 1 ; i <= m; i++){
		for(int j = 1; j <= n; j++){
			if(mx){
				add(i, j + m, a[i], -c[i][j]);
			}else{
				add(i, j + m, a[i], c[i][j]);
			}
		}
	}
	return EdmondsKarp(st, des);

}
int main(){
	
	while(cin >> m >> n){
		for(int i = 1; i <= m; i++){
			scanf("%d", &a[i]);
			//add(st, i, c, 0);
		}

		for(int i = 1; i <= n; i++){
			
			scanf("%d", &b[i]);
			//add(i + m, des, c, 0);
		}

		for(int i = 1; i <= m; i++){
			for(int j = 1; j <= n; j++){
				scanf("%d", &c[i][j]);
			}
		}
		printf("%d\n", solve(0));
		printf("%d\n", -solve(1));


	}

	return 0;
}

  

posted @ 2017-02-17 20:33  vwirtveurit  阅读(209)  评论(0编辑  收藏  举报