您的位置:首页 > 理论基础 > 计算机网络

网络流-最大流 Dinic模板

2018-04-10 22:08 477 查看
#include <bits/stdc++.h>

using namespace std;

#define MP make_pair
#define PB push_back
#define ls first
#define rs second
typedef long long LL;
typedef pair<int,int> PII;
const double eps=1e-8;
const double pi=acos(-1.0);
const int K=1e5+7;
const int mod=1e9+7;

vector<pair<int,int>>mp[K];
int n,m,cnt,flow[K*2],deep[K],cur[K];

int bfs(int s,int t)
{
queue<int>q;
memset(deep,0,sizeof deep);
q.push(s),deep[s]=1;
while(!q.empty())
{
int u=q.front();q.pop();
for(auto &it:mp[u])
if(!deep[it.ls]&&flow[it.rs])
{
deep[it.ls]=deep[u]+1;
q.push(it.ls);
if(it.ls==t)
return 1;
}
}
return 0;
}
int dfs(int x,int d,int t)
{
if(x==t) return d;
for(int i=cur[x];i<mp[x].size();cur[x]=++i)
{
int u=mp[x][i].ls,v=mp[x][i].rs;
if(deep[u]==deep[x]+1&&flow[v])
{
int td=min(d,dfs(u,min(d,flow[v]),t));
if(!td) continue;
flow[v]-=td;
flow[v^1]+=td;
return td;
}
}
return 0;
}
int dinic(int s,int t)
{
int ret=0,d;
while(bfs(s,t))
{
memset(cur,0,sizeof cur);
while(d=dfs(s,mod,t))    ret+=d;
}
return ret;
}
int main(void)
{
while(~scanf("%d%d",&m,&n))
{
cnt=0;
memset(mp,0,sizeof mp);
for(int i=0,u,v,w;i<m;i++)
{
scanf("%d%d%d",&u,&v,&w);
flow[cnt]=w,flow[cnt+1]=0;
mp[u].PB(MP(v,cnt++));
mp[v].PB(MP(u,cnt++));
}
printf("%d\n",dinic(1,n));
}
return 0;
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: