增广路算法---网络流

#include<queue>
#include<cstdio> 
#include<iostream>
#include<cstring>
using namespace std;

const int maxn = 20;
const int INF = (1<<30);

int cap[maxn][maxn],flow[maxn][maxn];//cap记录容量,flow记录流量
int m;  //弧的数量

int EdmondsKarp(int s,int t)
{
    int p[maxn],a[maxn];
    queue<int>q;
    
    memset(flow,0,sizeof(flow)); //初始化流量数组
    int f=0;
    
    while(true)
    {
        memset(a,0,sizeof(a));
        
        a[s]=INF;
        
        q.push(s);
        
        while(!q.empty())//BFS找增广路 
        {
            int u=q.front(); q.pop();
            
            for(int v=1;v<=n;v++) 
            if(!a[v] && cap[u][v]>flow[u][v]) //由于a[i]总是正数,所以使用a[i]代替vis数组。
            {
                //找新的节点v 
                p[v]=u; q.push(v);
                a[v]=min(a[u],cap[u][v]-flow[u][v]);    
            }     
        }
        
        if(a[t] == 0) break; //找不到,说明当前流已经是最大流
        
        for(int u=t;u!=s;u=p[u]) 
        {
            flow[p[u]][u] += a[t];//更新正向流量 
            flow[u][p[u]] -= a[t];//更新反向流量 
        }
        
        f += a[t]; //更新从s流出的流量 
    }
    
    return f;
     
}

int main(void)
{
    cin >> m;
    int u,v;
    for(int i=1;i<=m;i++)
    {
        cin >> u >> v;
        cin >> cap[u+1][v+1];
        cap[v+1][u+1]=0;    
    } 
    
    int f = EdmondsKarp(1,6);
    
    cout<< f;
    
    return 0; 
}


/*
10 
0 1 8 
0 2 4 
1 3 2 
1 4 2 
2 1 4 
2 3 1 
2 4 4 
3 4 6 
3 5 9 
4 5 7
*/

结果为8

猜你喜欢

转载自www.cnblogs.com/zuimeiyujianni/p/9016149.html