Augmenting Path Algorithm

#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 records capacity, flow records flow 
int m;   // number of arcs

int EdmondsKarp(int s,int t)
{
    int p[maxn],a[maxn];
    queue<int>q;
    
    memset(flow, 0 , sizeof (flow)); // initialize flow array 
    int f= 0 ;
    
    while(true)
    {
        memset(a,0,sizeof(a));
        
        a[s]=INF;
        
        q.push(s);
        
        while (!q.empty()) // BFS finds augmented path 
        {
             int u= q.front(); q.pop();
            
            for ( int v= 1 ;v<=n;v++ ) 
             if (!a[v] && cap[u][v]>flow[u][v]) // Because a[i] is always positive, so Use a[i] instead of the vis array. 
            {
                 // Find a new node v 
                p[v]= u; q.push(v);
                a[v]=min(a[u],cap[u][v]-flow[u][v]);    
            }     
        }
        
        if (a[t] == ​​0 ) break ; // can't find it, indicating that the current stream is already the maximum stream
        
        for(int u=t;u!=s;u=p[u]) 
        {
            flow[p[u]][u] += a[t]; // Update forward flow 
            flow[u][p[u]] -= a[t]; // Update reverse flow 
        }
        
        f += a[t]; // Update the flow from 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
*/

result is 8

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326523440&siteId=291194637