Cod sursa(job #2441816)

Utilizator PaterucAPetruc Andrei Stefan PaterucA Data 21 iulie 2019 12:25:33
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

ifstream inf("maxflow.in");
ofstream outf("maxflow.out");

const int N=1010;

int n, m, cap[N][N], vis[N];
int mf;

void bfs();

int main()
{
    inf>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x, y, z;
        inf>>x>>y>>z;
        cap[x][y]=z;
    }
    bfs();
    outf<<mf;

    return 0;
}

void bfs()
{
    int stp=1;
    queue<int> q;
    map<int,int> pth;
    q.push(1);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(int i=1; i<=n; i++)
        {
            if(cap[x][i]>0&&vis[i]<stp)
            {
                vis[i]=stp;
                q.push(i);
                pth[i]=x;
                if(i==n)
                {
                    int f=cap[x][i];
                    int aux=x;
                    do
                    {
                        f=min(f, cap[pth[aux]][aux]);
                        aux=pth[aux];
                    }while(aux>1);
                    mf+=f;
                    aux=x;
                    cap[x][i]-=f;
                    cap[i][x]+=f;
                    do
                    {
                        cap[pth[aux]][aux]-=f;
                        cap[aux][pth[aux]]+=f;
                        aux=pth[aux];
                    }while(aux>1);
                    pth.clear();
                    stp++;
                    while(!q.empty())
                        q.pop();
                    q.push(1);
                    break;
                }
            }
        }
    }
}