Cod sursa(job #2738424)

Utilizator CiboAndreiAndrei Cibo CiboAndrei Data 5 aprilie 2021 20:11:28
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <bits/stdc++.h>

using namespace std;

//#define f cin
//#define g cout
//ifstream f("data.in");
//ofstream g("data.out");
ifstream f("maxflow.in");
ofstream g("maxflow.out");

//#define int long long
//#define pii pair <int, int>

const int dim = 1e3 + 2;
const int mod = 100003;

int n, m;
int cap[dim][dim];

void nos(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
}

int readInt () {
    bool minus = false;
    int result = 0;
    char ch;
    ch = getchar();
    while (true) {
        if (ch == '-') break;
        if (ch >= '0' && ch <= '9') break;
        ch = getchar();
    }
    if (ch == '-') minus = true; else result = ch-'0';
    while (true) {
        ch = getchar();
        if (ch < '0' || ch > '9') break;
        result = result*10 + (ch - '0');
    }
    if (minus)
        return -result;
    else
        return result;
}

void read(){
    f >> n >> m;

    int x, y, z;

    for(int i = 1; i <= m; ++i){
        f >> x >> y >> z;
        cap[x][y] = z;
    }
}

int parent[dim];

bool bfs(int start, int finish){
    queue <int> q;
    q.push(start);

    bool mark[dim] = {};
    mark[start] = 1;

    while(!q.empty()){
        int nod = q.front(); q.pop();

        for(int i = 1; i <= n; ++i){
            if(mark[i] == 0 && cap[nod][i] > 0){
                parent[i] = nod;
                q.push(i);

                if(i == finish){
                    return 1;
                }
            }
        }
    }

    return 0;
}

void solve(){
    int ans = 0;

    while(bfs(1, n)){
        int mn = INT_MAX;

        for(int i = n; parent[i]; i = parent[i])
            mn = min(mn, cap[parent[i]][i]);

        ans += mn;

        for(int i = n; i; i = parent[i])
            cap[parent[i]][i] -= mn,
            cap[i][parent[i]] += mn;
    }

    g << ans;
}

void restart(){

}

int32_t main()
{
    nos();
    read();
    solve();
    //restart();

    return 0;
}