HDU 1532

本文详细解析了DrainageDitches问题中所使用的网络流算法,并提供了完整的C++实现代码。该问题通过建立一个从源点到汇点的流网络来模拟农田排水系统,使用增广路径算法(如BFS和DFS)寻找最大流,进而求解最优的排水方案。

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

题目链接 :Drainage Ditches


裸的网络流(当练习题不错!!

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
#define INF 9999999
struct Node{
	int to;
	int w;
	int ne;
}e[1000];
int head[1000],deth[1000];
int n,m,x,y,val,cnt;
queue<int>q;
void init()
{
	cnt = 0;
	memset(head,-1,sizeof(head));
	while(!q.empty())
		q.pop();
}
void add(int u,int v,int val)
{
	e[cnt].to = v;
	e[cnt].w = val;
	e[cnt].ne = head[u];
	head[u] = cnt ++;
}
int bfs()
{
	memset(deth,0,sizeof(deth));
	deth[1] = 1;
	q.push(1);
	while(!q.empty())
	{
		int k = q.front();
		q.pop();
		for(int i=head[k];~i;i=e[i].ne)
		{
			int t = e[i].to;
			if(e[i].w >0 && deth[t] == 0)
			{
				deth[t] = deth[k] + 1;
				q.push(t);
			}
		}
	}
	if(deth[m] == 0)
		return 0;
	return 1;
}
int dfs(int u,int dist)
{
	if(u == m)
	return dist;
	for(int i=head[u];~i;i=e[i].ne)
	{
		if(deth[e[i].to] == deth[u] + 1 && e[i].w != 0)
		{
			int di = dfs(e[i].to,min(dist,e[i].w));
			if(di>0)
			{
				e[i].w -= di;
				e[i^1].w += di;
				return di;
			}
		}
	}
	return 0;
}
long long dinic()
{
	long long ans = 0;
	while(bfs())
		while(int di = dfs(1,INF))
			ans += di;
	cout<<ans<<endl;
}
int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		init();
		for(int i=1;i<=n;i++)
		{
			scanf("%d%d%d",&x,&y,&val);
			add(x,y,val);
			add(y,x,0);
		}
		dinic();
	}
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值