Drainage Ditches
Time Limit: 1000 MS Memory Limit: 32768 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
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
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
Source
USACO 93
网络流模板题,直接按模板敲就行,代码把Ford-Fulkerson和Dinic算法都写了。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int MAXN = 409;
const int INF = 2147483647;
struct edge{
int cap,to,rev;
edge(int a = 0,int b = 0,int c = 0) :to(a),cap(b),rev(c){}
};
vector<edge> G[MAXN];
int level[MAXN];
int iter[MAXN];
void init()
{
for(int i = 0;i < MAXN;i++){
G[i].clear();
}
}
void Add(int f,int t,int c)
{
G[f].push_back(edge{t,c,G[t].size() } );
G[t].push_back(edge{f,0,G[f].size()-1} );
}
void bfs22(int s)
{
memset(level,-1,sizeof(level));
level[s] = 0;
queue<int > que;
que.push(s);
while(!que.empty()){
int v = que.front();
que.pop();
for(int i = 0;i < G[v].size();i++){
edge &e = G[v][i];//
if(e.cap > 0 && level[e.to] == -1){
level[e.to] = level[v]+1;
que.push(e.to);
}
}
}
}
int dfs22(int v,int t,int f)
{
if(v == t) return f;
for(int &i = iter[v];i < G[v].size();i++){
edge &e = G[v][i];
if(e.cap > 0 && level[v] < level[e.to]){
int d = dfs22(e.to,t,min(f,e.cap));
if(d > 0){
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int MAX11(int s,int t)
{
int f = 0;
while(true){
bfs22(s);
if(level[t] < 0){
return f;
}
memset(iter,0,sizeof(iter));
int temp;
while( (temp = dfs22(s,t,INF)) > 0){
f += temp;
}
}
}
int main()
{
int bsum,dsum;
while(scanf("%d%d",&bsum,&dsum) != EOF){
init();
for(int i = 0;i < bsum;i++){
int aa,bb,cc;
scanf("%d%d%d",&aa,&bb,&cc);
Add(aa,bb,cc);
}
int ans = 0;
ans = MAX11(1,dsum);
printf("%d\n",ans);
}
return 0;
}