Cod sursa(job #1411965)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 1 aprilie 2015 01:02:31
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 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>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

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

int n, m, x, y, z, add, maxflow, f[nmax], cap[nmax][nmax], flow[nmax][nmax];

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

bool bfs()
{
    memset(f, 0, sizeof(f));
    f[1] = 1;
    q.pb(1);

    while(!q.empty())
    {
        x = q.front();
        q.pop_front();

        if(x == n)
            continue;

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

    return (f[n] != 0);
}

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;
    }

    while(bfs())
    {
        for(auto it : v[n])
            if(f[it])
            {
                f[n] = it;
                add = inf;

                for(x = n; x != f[x]; x = f[x])
                    add = min(add, cap[f[x]][x] - flow[f[x]][x]);

                for(x = n; x != f[x]; x = f[x])
                {
                    flow[f[x]][x] += add;
                    flow[x][f[x]] -= add;
                }

                maxflow += add;
            }
    }

    printf("%d\n", maxflow);

    return 0;
}