poj 1273 Drainage Ditches

http://poj.org/problem?id=1273

最大流裸题  注意测试数据有重边的处理方法即可。

EK算法代码:

#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;
const int MAX = 210;
const LL INF = 1e18;

LL map[MAX][MAX];

queue <int> Q;
int N,M,pre[MAX];
bool BFS(int S, int T){///判断是否有增广路
	memset(pre, -1, sizeof(pre));
	while(!Q.empty()) Q.pop();
	Q.push(S);
	while(!Q.empty()){
		int u = Q.front();
		Q.pop();
		for(int i=1; i<=M; i++){
			if(pre[i] == -1 && map[u][i] > 0){
				pre[i] = u;
				if(i == T) return true;
				Q.push(i);
			}
		}
	}
	return false;
}

LL EK(int S, int T){///求解最大流
	LL maxflow = 0;
	while(BFS(S, T)){
		LL minflow = INF;
		for(int i=T; i!=S; i=pre[i])
			minflow = min(minflow, map[pre[i]][i]);
		for(int i=T; i!=S; i=pre[i]){
			map[pre[i]][i] -= minflow;
			map[i][pre[i]] += minflow;
		}
		maxflow += minflow;
	}
	return maxflow;
}

int main(){
	while(scanf("%d%d",&N,&M) == 2){
		memset(map, 0, sizeof(map));
		int S = 1, T = M;
		int u,v;
		LL cap;
		for(int i=0; i<N; i++){
			scanf("%d%d%lld",&u,&v,&cap);
			map[u][v] += cap;
		}
		printf("%lld\n",EK(S,T));
	}
	return 0;
}

Dinik算法代码

#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>

using namespace std;

const int MAX = 250;
const int INF = 0x3f3f3f3f;

int map[MAX][MAX],level[MAX],N,M;

queue <int> Q;
bool BFS(){///构建层次图
	memset(level, -1, sizeof(level));
	level[1] = 0;
	Q.push(1);
	while(!Q.empty()){
		int u = Q.front();
		Q.pop();
		for(int i=1; i<=M; i++){
			if(level[i] == -1 && map[u][i] > 0){
				level[i] = level[u] + 1;
				Q.push(i);
			}
		}
	}
	if(level[M] > 0) return true;
	return false;
}

int DFS(int id, int minflow){///计算增广路上最小的流量值
	if(id == M) return minflow;
	int a = 0;
	for(int i=1; i<=M; i++){
		if(map[id][i] && level[i] == level[id] + 1
			&& (a = DFS(i, min(map[id][i], minflow)))){
			map[id][i] -= a;
			map[i][id] += a;
			return a;
		}
	}
	return 0;
}

int main(){
	while(scanf("%d%d",&N,&M) == 2){
		memset(map, 0, sizeof(map));
		for(int i=0; i<N; i++){
			int u,v,cap;
			scanf("%d%d%d",&u,&v,&cap);
			map[u][v] += cap;
		}
		int tmp, ans = 0;
		while(BFS()){///BFS为假时代表汇点不在层次图中 无法进行增广过程
			while(tmp = DFS(1, INF)) ans += tmp;///累加每次增广路上增大的流量值
		}
		printf("%d\n",ans);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值