题目链接:模板网络最大流
粘上几篇博客:
这几篇博客对网络流解释的都很详细,我就不赘述了(其实是我不会说 233333.....
题是裸的网络流问题,代码如下
#include<iostream>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e6+5;
const int INF=9999999;
struct Node{
int to;
int w;
int ne;
}e[maxn];
int head[maxn],deth[maxn];
int n,m,s,t,cnt; // s为源点 t 为汇点
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[s] = 1;
q.push(s);
while(!q.empty())
{
int k = q.front();
q.pop();
for(int i=head[k];~i;i=e[i].ne)
{
if(e[i].w > 0 && deth[e[i].to] == 0)
{
deth[e[i].to] = deth[k] + 1;
q.push(e[i].to);
}
}
}
if(deth[t]!=0) // 检测是否可以分层
{
return 1;
}
else
return 0;
}
int dfs(int u,int dist)
{
if( u == t)
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) // 如果残量 > 0
{
e[i].w -= di;
e[i^1].w += di;
return di;
}
}
}
return 0;
}
int dinic() // 用来分层
{
int ans = 0;
while(bfs()) // 如果可以分层
{
while(int di = dfs(s,INF)) // 加上求出的这条路上的最小流
ans += di;
}
return ans;
}
int main()
{
cin>>n>>m>>s>>t;
int x,y,val;
init();
for(int i=1;i<=m;i++)
{
cin>>x>>y>>val;
add(x,y,val);
add(y,x,0);
}
cout<<dinic()<<endl;
return 0;
}