poj 1273 Drainage Ditches 最大流入门题

时间:2023-02-08 20:36:38

题目链接:http://poj.org/problem?id=1273

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.

题意描述:源点为1,汇点为n,源点处是水池,通过水沟排水到汇点河流,问最大排水量。

算法分析:最大流的模型,每条水沟有最大的排水量,通过建模dinic一遍就ok了。

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#define inf 0x7fffffff
using namespace std;
const int maxn=+; int n,m,from,to;
struct node
{
int v,flow;
int next;
}edge[maxn*];
int head[maxn],edgenum; void add(int u,int v,int flow)
{
edge[edgenum].v=v ;edge[edgenum].flow=flow ;
edge[edgenum].next=head[u] ;head[u]=edgenum++; edge[edgenum].v=u ;edge[edgenum].flow=;
edge[edgenum].next=head[v] ;head[v]=edgenum++;
} int d[maxn];
int bfs()
{
memset(d,,sizeof(d));
d[from]=;
queue<int> Q;
Q.push(from);
while (!Q.empty())
{
int u=Q.front() ;Q.pop() ;
for (int i=head[u] ;i!=- ;i=edge[i].next)
{
int v=edge[i].v;
if (!d[v] && edge[i].flow)
{
d[v]=d[u]+;
Q.push(v);
if (v==to) return ;
}
}
}
return ;
} int dfs(int u,int flow)
{
if (u==to || flow==) return flow;
int cap=flow;
for (int i=head[u] ;i!=- ;i=edge[i].next)
{
int v=edge[i].v;
if (d[v]==d[u]+ && edge[i].flow)
{
int x=dfs(v,min(cap,edge[i].flow));
edge[i].flow -= x;
edge[i^].flow += x;
cap -= x;
if (cap==) return flow;
}
}
return flow-cap;
} int dinic()
{
int ans=;
while (bfs()) ans += dfs(from,inf);
return ans;
} int main()
{
while (scanf("%d%d",&m,&n)!=EOF)
{
memset(head,-,sizeof(head));
edgenum=;
int a,b,c;
for (int i= ;i<m ;i++)
{
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
from=;
to=n;
printf("%d\n",dinic());
}
return ;
}