Cod sursa(job #1290696)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 11 decembrie 2014 18:10:45
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>

using namespace std;

const int nmax = 1005;
const int inf = (1LL << 31) - 1;

int n, m, x, y, z, source, sink, sol, add, f[nmax], cap[nmax][nmax], flow[nmax][nmax];

vector<int> v[nmax];
queue<int> q;

bool bfs(int x)
{
    memset(f, 0, sizeof(f));
    f[source] = source;
    q.push(source);

    while(!q.empty())
    {
        x = q.front();
        q.pop();
        if(x == sink) continue;

        for(auto it : v[x])
            if(!f[it] && flow[x][it] < cap[x][it])
            {
                f[it] = x;
                q.push(it);
            }
    }

    return f[sink];
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    scanf("%d%d", &n, &m);

    for(; m; m--)
    {
        scanf("%d%d%d", &x, &y, &z);
        v[x].pb(y);
        v[y].pb(x);
        cap[x][y] = z;
    }

    source = 1;
    sink = n;

    while(bfs(source))
    {
        for(auto it : v[sink])
            if(f[it])
            {
                f[sink] = it;
                add = inf;
                for(x = sink; f[x] != x; x = f[x])
                    add = min(add, cap[f[x]][x] - flow[f[x]][x]);
                for(x = sink; f[x] != x; x = f[x])
                {
                    flow[f[x]][x] += add;
                    flow[x][f[x]] -= add;
                }
                sol += add;
            }
    }
    printf("%d\n", sol);

    return 0;
}