網絡流

https://www.cnblogs.com/zsboy/archive/2013/01/27/2878810.html

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define MN 1005
using namespace std;
typedef long long LL;
const int INF=0x3f3f3f3f;
//只有一個容量的變量 
int c[MN][MN],s,t,n,m,f[MN],pre[MN],sum;
queue<int> q;
int bfs()
{
    s=1,t=n; 
    f[s]=INF;
    memset(pre,-1,sizeof pre);
    pre[s]=0;//s點的前驅是0,其餘都是-1 
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        if(u==t) break;
        for(int v=1;v<=n;v++)//尋找最小的流量(容量) 
        {
//          if(c[u][v]==0)continue; //如果不連接相當於斷了的,如果連接且沒有容量了,也相當於斷了 
            if(c[u][v]>0 && pre[v]==-1) 
            {
                f[v]=min(f[u],c[u][v]);//迭代法去求留到t的流量
                pre[v]=u;           
                q.push(v); 
            }
        }
    }
    if(f[t]>0)
    {
        for(int i=t;i!=s;i=pre[i])
        {
            c[pre[i]][i]-=f[t];
            c[i][pre[i]]+=f[t];
        }
        return f[t];    
    }
    return 0;
}
void ek()
{
    int tmp=bfs();
    while(tmp>0)
    {
        sum+=tmp;
        tmp=bfs();
    }
}
int u,v,w;
int main()
{
    scanf("%d%d",&n,&m);
    memset(f,0,sizeof f);
    memset(c,0x3f,sizeof c);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&u,&v,&w);
        c[u][v]+=w;
    }
    ek();
    cout<<sum<<endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章