题意:将水从池塘(1)通过沟渠输送到溪流(M),期中有多个调节器(节点)可以调节水流,每条沟渠有最大流速,问水从池塘中排到溪流的最大速率。
分析,这题是一道很典型的图论网络流问题,按照题目所给边建图之后直接用最大流Dinic算法即可,注意多组输入!!!
ac代码:
/*
author:wuzx
*/
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<utility>
#include<string>
#include<queue>
#include<map>
#include<set>
#include<iterator>
#include<iomanip>
#include<stack>
#include<cstdio>
#define ll long long
//#define int long long
#define endl "\n"
#define P pair<int,int>
#define f first
#define s second
#define double long double
using namespace std;
typedef unsigned long long ull;
const int maxn=210;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
using namespace std;
struct Edge{
int from,to,cap,flow;
};
//封装好的Dinic算法模板
struct Dinic{
int n,m,s,t;
vector<Edge> edge;
vector<int> g[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init(int n)
{
for(int i=1;i<=n;i++)
g[i].clear();
edge.clear();
}
void ClearFlow()
{
for(int i=0;i<edge.size();i++)
edge[i].flow=0;
}
void add(int from,int to,int cap)
{
edge.push_back(Edge{from,to,cap,0});
edge.push_back(Edge{to,from,0,0});
m=edge.size();
g[from].push_back(m-2);
g[to].push_back(m-1);
}
bool bfs()
{
memset(vis,0,sizeof vis);
queue<int> q;
q.push(s);
vis[s]=1;
d[s]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
for(int i=0;i<g[x].size();i++)
{
Edge& e=edge[g[x][i]];
if(!vis[e.to]&&e.cap>e.flow)
{
vis[e.to]=1;
d[e.to]=d[x]+1;
q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int x,int a)
{
if(x==t||a==0)
return a;
int flow=0,f;
for(int& i=cur[x];i<g[x].size();i++)
{
Edge& e=edge[g[x][i]];
if(d[x]+1==d[e.to]&&(f=dfs(e.to,min(a,e.cap-e.flow)))>0)
{
e.flow+=f;
edge[g[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(a==0)
break;
}
}
return flow;
}
int maxflow(int s,int t)//最大流算法
{
this->s=s;this->t=t;
int flow=0;
while(bfs())
{
memset(cur,0,sizeof cur);
flow+=dfs(s,inf);
}
return flow;
}
};
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int n,m;
while(cin>>n>>m)
{
int ff,tt,cc;
Dinic dd;
dd.init(m);
dd.ClearFlow();
for(int i=0;i<n;i++)
{
cin>>ff>>tt>>cc;
dd.add(ff,tt,cc);//加边
}
cout<<dd.maxflow(1,m)<<endl;//直接调用最大流输入
}
return 0;
}