Cod sursa(job #2742729)

Utilizator MagnvsDaniel Constantin Anghel Magnvs Data 21 aprilie 2021 16:54:24
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

const int nmax = 1000, cmax = 110000;

vector <int> g[nmax+1];
int c[nmax+1][nmax+1];

queue <int> q;
int r[nmax+1];

int main( ) {
    int n, m;
    fin >> n >> m;
    for ( int i = 1; i <= m; ++ i ) {
        int x, y, z;
        fin >> x >> y >> z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }

    int sol = 0;
    r[n] = -1;
    while ( r[n] != 0 ) {
        for ( int i = 1; i <= n; ++ i ) {
            r[i] = 0;
        }
        q.push(1);
        r[1] = -1;

        while ( q.empty() == 0 ) {
            int x = q.front();
            q.pop();

            for ( int i = 0; i < int(g[x].size()); ++ i ) {
                int xn = g[x][i];
                if ( r[xn] == 0 && c[x][xn] > 0 ) {
                    r[xn] = x;
                    q.push(xn);
                }
            }
        }

        if ( r[n] != 0 ) {
            for ( int i = 0; i < int(g[n].size()); ++ i ) {
                int x = g[n][i];
                if ( c[x][n] > 0 ) {
                    int aux = c[x][n];
                    while ( x != 1 ) {
                        if ( aux > c[r[x]][x] ) {
                            aux = c[r[x]][x];
                        }
                        x = r[x];
                    }
                    if ( aux > 0 ) {
                        sol += aux;
                        x = g[n][i];
                        c[x][n] -= aux;
                        c[n][x] += aux;
                        while ( x != 1 ) {
                            c[r[x]][x] -= aux;
                            c[x][r[x]] += aux;
                            x = r[x];
                        }
                    }
                }
            }
        }
    }

    fout << sol << "\n";

    return 0;
}