码迷,mamicode.com
首页 > 其他好文 > 详细

网络流

时间:2018-10-16 15:54:11      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:sed   ret   std   math   cstring   false   algo   反向   namespace   

技术分享图片
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 2000010;
const int maxm=1010;
const int inf =0x3f3f3f3f;
int head[maxn],dis[maxn];
struct Edge
{
    int to,next,f;
}edge[maxm]; //链式前向星 
int s,t,cnt;
void add(int u,int v,int f)
{
    edge[cnt].to=v;
    edge[cnt].f=f;
    edge[cnt].next=head[u];
    head[u]=cnt++; //正向建边 
    edge[cnt].to=u;
    edge[cnt].f=0;
    edge[cnt].next=head[v];
    head[v]=cnt++;  //反向建边 
} 
bool bfs() //增广路 
{
    memset(dis,-1,sizeof(dis));
    queue <int> que;
    dis[s]=0;
    que.push(s);
    while(!que.empty())
    {
        int u=que.front();
        que.pop();
        for(int i=head[u];i!=-1;i=edge[i].next)
        {
            int v=edge[i].to;
            int f=edge[i].f;
            if(dis[v]==-1&&f>0)
            {
                dis[v]=dis[u]+1;
                if(v==t) return true;
                que.push(v);
            }
        }
    }
    return false;
} 
int dfs(int x,int maxf) //更新 
{
    if(x==t||maxf==0) return maxf;
    int flow=0;
    for(int i=head[x];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        int f=edge[i].f;
        if(dis[v]==dis[x]+1&&f>0)
        {
            f=dfs(v,min(f,maxf-flow));
            edge[i].f-=f;
            edge[i^1].f+=f;
            flow+=f;
            if(flow==maxf) return flow;
        }
    }
    return flow;
}
int main()
{
    int T,cas=0,n,m,k;
    scanf("%d",&T);
    while(T--)
    {
        cnt=0;
        memset(head,-1,sizeof(head));
        scanf("%d%d",&n,&m); // 起点 汇点 
        s=1,t=n;
        for(int i=0;i<m;i++)
        {
            int u,v,f;
            scanf("%d%d%d",&u,&v,&f);
            add(u,v,f);  //加边 
        }
        int ans=0;
        while(bfs())
        {
            ans+=dfs(s,inf);
        }
        cout<<ans<<endl;
    }
    
    
} 
最大流-dinc

 

网络流

标签:sed   ret   std   math   cstring   false   algo   反向   namespace   

原文地址:https://www.cnblogs.com/ww123/p/9797909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!