hdu1532 网络流裸题

本文探讨了如何通过建立排水沟渠系统解决雨水覆盖草地的问题。利用网络流算法,特别是最大流最小割原理,确定从水塘到河流的最大排水速率。通过对每条沟渠的流向及容量进行详细建模,并采用广度优先搜索来寻找增广路径,最终求解出最大流量。

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

纪念我的第一个网络流裸题

ek的算法 具体可看我的上一篇博客

Drainage Ditches

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18437    Accepted Submission(s): 8721


Problem Description
Every time it rains on Farmer John's fields, a pond forms over Bessie's favorite clover patch. This means that the clover is covered by water for awhile and takes quite a long time to regrow. Thus, Farmer John has built a set of drainage ditches so that Bessie's clover patch is never covered in water. Instead, the water is drained to a nearby stream. Being an ace engineer, Farmer John has also installed regulators at the beginning of each ditch, so he can control at what rate water flows into that ditch. 
Farmer John knows not only how many gallons of water each ditch can transport per minute but also the exact layout of the ditches, which feed out of the pond and into each other and stream in a potentially complex network. 
Given all this information, determine the maximum rate at which water can be transported out of the pond and into the stream. For any given ditch, water flows in only one direction, but there might be a way that water can flow in a circle. 
 

Input
The input includes several cases. For each case, the first line contains two space-separated integers, N (0 <= N <= 200) and M (2 <= M <= 200). N is the number of ditches that Farmer John has dug. M is the number of intersections points for those ditches. Intersection 1 is the pond. Intersection point M is the stream. Each of the following N lines contains three integers, Si, Ei, and Ci. Si and Ei (1 <= Si, Ei <= M) designate the intersections between which this ditch flows. Water will flow through this ditch from Si to Ei. Ci (0 <= Ci <= 10,000,000) is the maximum rate at which water will flow through the ditch.
 

Output
For each case, output a single integer, the maximum rate at which water may emptied from the pond. 
 

Sample Input
  
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
 

Sample Output
  
50
 

Source

#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define ll long long
#define read(a) scanf("%d",&a);
using namespace std;
const int maxn=205;
const int inf=99999999;
int c[maxn][maxn];
bool book[maxn];
int pre[maxn];
int main(){
	freopen("test.txt","r",stdin);
	int start,end,weight;
	int n,m;
	int i,j;
	int ans;
	while(~scanf("%d %d",&m,&n)){
		memset(c,0,sizeof(c));
		for(i=0;i<m;i++){
			scanf("%d %d %d",&start,&end,&weight);
			c[start][end]+=weight;
		}
		ans=0;
		while(1){
			memset(book,false,sizeof(book));
			memset(pre,0,sizeof(pre));
			queue<int>que;
			que.push(1);
			book[1]=true;
			int mini=inf;
			while(!que.empty()){
				int num=que.front();
				if(num==n)
					break;
				//printf("%d\n",num);
				for(i=1;i<=n;i++){
					if(book[i]==false&&c[num][i]>0){
						book[i]=true;
						que.push(i);
						pre[i]=num;
						//printf("%d ",i);
						mini=min(mini,c[num][i]);
					}
				}
				//printf("\n");
				que.pop();
			}
			//printf("%d\n",mini);
			if(book[n]==false){
				//printf("!!!!!!");
				break;
			}
			int tmp=n;
			while(pre[tmp]!=0){
				c[pre[tmp]][tmp]-=mini;
				c[tmp][pre[tmp]]+=mini;
				tmp=pre[tmp];
			}
			ans+=mini;
			//printf("%d\n",ans);
		}
		printf("%d\n",ans);
	}
	return 0;
}


### 关于网络流算法的模板网络流是一种经典的图论算法,主要用于解决最大流、最小割等问。以下是几个常见的网络流算法模板及其对应的经典目。 #### 1. 最大流问 最大流问网络流中最基本的问之一,通常可以通过 **Edmonds-Karp 算法** 或者 **Dinic 算法** 解决。下面是一个简单的 Edmonds-Karp 算法实现: ```python from collections import deque class Edge: def __init__(self, v, flow, rev): self.v = v self.flow = flow self.rev = rev def add_edge(u, v, capacity, graph): edge_u_to_v = Edge(v, capacity, len(graph[v])) edge_v_to_u = Edge(u, 0, len(graph[u])) graph[u].append(edge_u_to_v) graph[v].append(edge_v_to_u) def bfs(s, t, parent, graph): visited = [False] * len(graph) queue = deque([s]) visited[s] = True while queue: u = queue.popleft() for idx, edge in enumerate(graph[u]): if not visited[edge.v] and edge.flow > 0: queue.append(edge.v) visited[edge.v] = True parent[edge.v] = u if edge.v == t: return True return False def edmonds_karp(n, s, t, graph): parent = [-1] * n max_flow = 0 while bfs(s, t, parent, graph): path_flow = float('Inf') v = t while v != s: u = parent[v] path_flow = min(path_flow, graph[u][next(i for i, e in enumerate(graph[u]) if e.v == v)].flow) v = u v = t while v != s: u = parent[v] index = next(i for i, e in enumerate(graph[u]) if e.v == v) graph[u][index].flow -= path_flow graph[v][graph[u][index].rev].flow += path_flow v = u max_flow += path_flow return max_flow ``` 上述代码实现了基于 BFS 的 Edmonds-Karp 算法来求解最大流问[^4]。 --- #### 2. 最小费用最大流问 如果需要考虑每条边的成本,则可以使用 **SPFA** 或 **Bellman-Ford** 结合最短路径的思想来计算最小费用的最大流。以下是一个 SPFA 实现的例子: ```python import heapq INF = int(1e9) def spfa_min_cost_max_flow(n, edges, start, end): adj_list = [[] for _ in range(n)] residual_graph = [[None]*n for _ in range(n)] for u, v, cap, cost in edges: adj_list[u].append((v, cap, cost)) adj_list[v].append((u, 0, -cost)) dist = [INF] * n potential = [0] * n prev_node = [-1] * n prev_edge = [-1] * n total_flow = 0 total_cost = 0 while True: pq = [] dist[start] = 0 heapq.heappush(pq, (dist[start], start)) while pq: d, node = heapq.heappop(pq) if d > dist[node]: continue for idx, (neighbor, cap, cost) in enumerate(adj_list[node]): if cap > 0 and dist[neighbor] > dist[node] + cost + potential[node] - potential[neighbor]: dist[neighbor] = dist[node] + cost + potential[node] - potential[neighbor] prev_node[neighbor] = node prev_edge[neighbor] = idx heapq.heappush(pq, (dist[neighbor], neighbor)) if dist[end] == INF: break for i in range(n): potential[i] += dist[i] flow = INF cur = end while cur != start: previous = prev_node[cur] edge_index = prev_edge[cur] flow = min(flow, adj_list[previous][edge_index][1]) cur = previous total_flow += flow total_cost += flow * potential[end] cur = end while cur != start: previous = prev_node[cur] edge_index = prev_edge[cur] adj_list[previous][edge_index] = ( adj_list[previous][edge_index][0], adj_list[previous][edge_index][1] - flow, adj_list[previous][edge_index][2] ) back_edge_index = None for j, (back_neighbor, _, _) in enumerate(adj_list[cur]): if back_neighbor == previous: back_edge_index = j break adj_list[cur][back_edge_index] = ( adj_list[cur][back_edge_index][0], adj_list[cur][back_edge_index][1] + flow, adj_list[cur][back_edge_index][2] ) cur = previous return total_flow, total_cost ``` 该代码通过调整势能函数优化了 SPFA,在处理负权边时更加高效[^5]。 --- #### 3. 经典模板推荐 以下是几道经典的网络流算法模板,适合初学者练习: 1. **POJ 1273 Drainage Ditches**: 这是一道典型的 Edmonds-Karp 算法入门。 2. **HDU 3549 Flow Problem**: 需要使用 Dinic 算法提高效率。 3. **Codeforces Round #XXX Div.2 C**: 涉及到最小费用最大流的应用场景。 4. **LeetCode 787 Cheapest Flights Within K Stops**: 虽然不是纯网络流,但可以用类似思路建模。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值