【图论03】网络流 1001 Drainage Ditches

本文介绍了一种基于网络流的Edmonds-Karp(EK)算法实现,通过BFS寻找增广路径来解决最大流问题。该算法适用于解决含有平行边的情况,并提供了完整的C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法思路:网络流。

比较简单的模板题,bfs实现的EK算法,算法框架来自刘汝佳的《算法竞赛》。maxflow(int s, int t)中的s, t分别代表源点和汇点。

不过要注意:

1.有多个case;

2.会有平行边,输入的时候相加就行了。

测试数据:

3 3
1 2 5
1 2 6
2 3 10

ans=10

 

//模板开始
#include <string>   
#include <vector>   
#include <algorithm>   
#include <iostream>   
#include <sstream>   
#include <fstream>   
#include <map>   
#include <set>   
#include <cstdio>   
#include <cmath>   
#include <cstdlib>   
#include <ctime>
#include <iomanip>
#include <string.h>
#include <queue>
#define SZ(x) (int(x.size()))
using namespace std;

int toInt(string s){
	istringstream sin(s); 
	int t; 
	sin>>t; 
	return t;
}
template<class T> string toString(T x){
	ostringstream sout; 
	sout<<x; 
	return sout.str();
}
typedef long long int64;
int64 toInt64(string s){
	istringstream sin(s); 
	int64 t; 
	sin>>t;
	return t;
}
template<class T> T gcd(T a, T b){ 
	if(a<0) 
		return gcd(-a, b);
	if(b<0) 
		return gcd(a, -b);
	return (b == 0)? a : gcd(b, a % b);
}
//模板结束(通用部分)

#define ifs cin

#define MAXN 250

int flow[MAXN][MAXN];
queue<int> q;
int f;
int a[MAXN];
int n, m;
int cap[MAXN][MAXN];
int p[MAXN];
#define INF 1<<30;

int maxflow(int s, int t)
{
	memset(flow, 0, sizeof(flow));
	f = 0;
	for( ; ; )
	{
		memset(a, 0, sizeof(a));
		a[s] = INF;
		q.push(s);
		while(!q.empty())
		{
			int u = q.front();
			q.pop();
			for(int v = 1; v <= n; v++)
			{
				if(!a[v] && cap[u][v] > flow[u][v])
				{
					p[v] = u;
					q.push(v);
					if(a[u] >= cap[u][v] - flow[u][v])
					{
						a[v] = cap[u][v] - flow[u][v]; 
					}
					else
					{
						a[v] = a[u];
					}
				}
			}
		}
		if(a[t] == 0)
		{
			break;
		}
		for(int u = t; u != s; u = p[u])
		{
			flow[p[u]][u] += a[t];
			flow[u][p[u]] -= a[t];
		}
		f += a[t];
	}
	return f;
}

//【图论03】网络流 1001 Drainage Ditches

int main()
{
	//ifstream ifs("shuju.txt", ios::in);
	while(ifs>>n>>m)
	{
		for(int i = 1; i <= m; i++)
		{
			for(int j = 1; j <= m; j++)
			{
				cap[i][j] = 0;
			}
		}
		int a, b, c;
		for(int i = 0; i < n; i++)
		{
			ifs>>a>>b>>c;
			cap[a][b] += c;
		}
		int f = maxflow(1, m);
		cout<<f<<endl;
	}

	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值