Cod sursa(job #3202639)

Utilizator octavi26octavian octavi26 Data 12 februarie 2024 08:15:37
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
#define N 1004

using namespace std;

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

int n, m;
int sursa;
struct muchie{
    int f, c;
    int type;
} M[N][N];
vector<int> g[N];

void Citire()
{
    int i;
    int x, y, c;
    fin >> n >> m;
    sursa = 1;
    for( i=1; i<=m; i++ ){
        fin >> x >> y >> c;
        g[x].push_back(y);  M[x][y] = {0, c, +1};
        g[y].push_back(x);  M[y][x] = {0, c, -1};
    }
}

bool ok;
int Dad[N];
bool viz[N];
queue<int> Q;
void BFS()
{
    while(!Q.empty())Q.pop();
    for( int i=1; i<=n; i++ )
        Dad[i] = -1, viz[i] = 0;
    Dad[sursa] = 0;
    Q.push(sursa);
    while( !Q.empty() )
    {
        int nod = Q.front();
        Q.pop();
        if( nod == n ) ok = 0;
        for( auto next : g[nod] )if( !viz[next] ){
            if( (M[nod][next].type < 0 && M[nod][next].f == 0) ||
                (M[nod][next].type > 0 && M[nod][next].f == M[nod][next].c) )
                continue;

            viz[nod] = 1;
            Dad[next] = nod;
            Q.push(next);

        }
    }
}

void Revizuire( int x, int &mn )
{
    if( x == sursa ) return;
    int type = M[ Dad[x] ][x].type;
    int f = M[ Dad[x] ][x].f;
    int c = M[ Dad[x] ][x].c;
    mn = min( mn, (type > 0) ? c - f : f );
    Revizuire( Dad[x], mn );
    M[ Dad[x] ][x].f += type*mn;
}

void Rezolvare()
{
    int i;
    ///Ford_Fulkerson
    ok = 0;
    while(!ok)
    {
        ok = 1;
        BFS();
        int mn = 2e9;
        if(!ok)Revizuire( n, mn );
    }

    int F = 0;
    for( auto next : g[sursa] ) F += M[sursa][next].f;
    fout << F;
}

int main()
{
    Citire();
    Rezolvare();
    return 0;
}