最小费用最大流

Description

给出一个\(N\)个点\(M\)条边的有向图,每条边上有一个容量限制\(cap\)和单位流量的花费\(cost\)。给出源点\(s\)和汇点\(t\),求从源点\(s\)到汇点\(t\)的花费最小的最大流。输出最小花费和最大流的值。

Solution

如果没有最小花费的限制,只需要不断在残余网络上找增广路即可,如果有最小花费限制,就把每次简单找增广路改为,在以花费为权值的图上,找从\(s\)\(t\)的最短路,每次沿最短路增广。这样就保证了每次增广得到的都是在当前流量下花费最小的流。

Code

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 1e3 + 10;
const int M = 2e3 + 10;

struct Edge 
{
	int from, to, next, cap, cost;
	Edge() {}
	Edge(int from, int to, int next, int cap, int cost) : 
		from(from), to(to), next(next), cap(cap), cost(cost) {}
} edge[M];
int head[N], tot;

void add(int from, int to, int cap, int cost) 
{
	edge[tot] = Edge(from, to, head[from], cap, cost);
	head[from] = tot++;
	edge[tot] = Edge(to, from, head[to], 0, -cost);
	head[to] = tot++;
}

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

int dis[N], pre[N];
bool vis[N];
queue<int> q;
bool spfa(int s, int t) 
{
	while (!q.empty()) q.pop();
	memset(dis, 0x3f, sizeof(dis));
	memset(vis, false, sizeof(vis));
	memset(pre, -1, sizeof(pre));
	q.push(s); vis[s] = true; dis[s] = 0;     
	while (!q.empty()) 
	{
		int u = q.front(); q.pop(); vis[u] = false;
		for (int i = head[u]; i != -1; i = edge[i].next) 
			if (edge[i].cap && dis[u] + edge[i].cost < dis[edge[i].to]) 
			{
				int v = edge[i].to;
				dis[v] = dis[u] + edge[i].cost;
				pre[v] = i;
				if (!vis[v]) q.push(v), vis[v] = true;
			}
	}
	return dis[t] < INF; 
}

int mcmf(int s, int t, int& maxflow) 
{
	int mincost = 0;
	maxflow = 0;
	while (spfa(s, t)) 
	{
		int flow = INF;
		for (int i = pre[t]; i != -1; i = pre[edge[i].from]) 
			flow = min(flow, edge[i].cap);
		for (int i = pre[t]; i != -1; i = pre[edge[i].from]) 
		{
			edge[i].cap -= flow;
			edge[i ^ 1].cap += flow;
			mincost += edge[i].cost * flow;
		}
		maxflow += flow;
	}
	return mincost;
}

int main()
{
	int n, m;
	scanf("%d%d", &n, &m);
	init();
	while (m--)
	{
		int u, v, cap, cost;
		scanf("%d%d%d%d", &u, &v, &cap, &cost);
		add(u, v, cap, cost);
	}
	int s, t, maxflow;
	scanf("%d%d", &s, &t);
	int mincost = mcmf(s, t, maxflow);
	printf("%d %d\n", mincost, maxflow);
	return 0;
}

Input

第一行给出两个整数n和m,表示结点数和边数。
接下来m行,每行给出4个整数u,v,w,c,表示从u到v有一条容量为w,单位流量花费为c的边。
最后一行给出两个整数s和t,表示源点和汇点。

Output

输出两个整数,分别表示最小花费和最大流。

Sample Input

5 5
1 2 2 2
1 3 3 2
2 4 3 1
3 4 2 3
4 5 2 1
1 5

Sample Output

8 2
posted @ 2017-08-14 16:27  达达Mr_X  阅读(179)  评论(0编辑  收藏  举报