码迷,mamicode.com
首页 > 编程语言 > 详细

hdu 1532 Drainage Ditches(edmond-karp最大流算法)

时间:2016-07-23 15:16:32      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1532

#include <stdio.h>
#include <queue>
#include <string.h>
#include <algorithm>
#define INT_MAX (int)1e9
using namespace std;

const int N = 207;

int network[N][N], pre[N], used[N], flow[N], n, m;                          //pre存储bfs过程中路径,used确保每次bfs对每个节点只遍历一次,flow辅助求bfs过程中的最小流
queue <int> q;

int BFS()
{
	memset(used, 0, sizeof(used));
	memset(flow, -1, sizeof(flow));
	while (!q.empty())
		q.pop();
	for (int i = 1; i <= m; i++)
		pre[i] = i;
	flow[1] = INT_MAX;
	q.push(1);
	while (!q.empty())
	{
		int temp = q.front();
		q.pop();
		for (int i = 1; i <= m; i++)
		{
			if (!used[i] && network[temp][i])
			{
				pre[i] = temp;
				flow[i] = min(flow[temp], network[temp][i]);
				used[i] = 1;
				q.push(i);
			}
		}
	}
	if (flow[m] == -1)
		return 0;
	else
		return flow[m];
}

int edmond_karp()                                                            //bfs找到最小流,正向减去最小流,并且反向增加最小流
{
	int ans = 0, minFlow;
	while (minFlow = BFS())
	{
		ans += minFlow;
		int r = m;
		while (r != 1)
		{
			network[r][pre[r]] += minFlow;
			network[pre[r]][r] -= minFlow;
			r = pre[r];
		}
	}
	return ans;
}

int main()
{
	while (scanf("%d%d", &n, &m) != EOF)
	{
		memset(network, 0, sizeof(network));
		for (int i = 1; i <= n; i++)
		{
			int u, v, w;
			scanf("%d%d%d", &u, &v, &w);
			network[u][v] += w;
		}
		int ans = edmond_karp();
		printf("%d\n", ans);
	}
	return 0;
}

 

hdu 1532 Drainage Ditches(edmond-karp最大流算法)

标签:

原文地址:http://www.cnblogs.com/burning-flame/p/5698613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!