题目链接 :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;
}