Cod sursa(job #1784641)

Utilizator team_nameUPB Banu Popa Visan team_name Data 20 octombrie 2016 12:20:11
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

const int nmax = 1010;
const int inf = 0x3f3f3f3f;

int n, m, x, y, z, cap[nmax][nmax], flow[nmax][nmax], father[nmax];
bool used[nmax];
int source, sink;
vector<int> g[nmax];

bool bfs()
{
    for (int i = 1; i <= n; ++ i)
        used[i] = father[i] = 0;
    queue<int> q;
    q.push(source);

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

        if (node == sink) return 1;
        for (int vec : g[node])
            if (!used[vec] && cap[node][vec] > flow[node][vec])
            {
                used[vec] = 1;
                father[vec] = node;
                q.push(vec);
            }
    }
    return 0;
}

int get_maxflow()
{
    int ans = 0;
    while (bfs())
    {
        for (int vec : g[sink])
            if (used[vec] && cap[vec][sink] != flow[vec][sink])
            {
                father[sink] = vec;
                int minflow = inf;
                for (int node = sink; node != source; node = father[node])
                    minflow = min(minflow, cap[father[node]][node] - flow[father[node]][node]);
                for (int node = sink; node != source; node = father[node])
                {
                    flow[father[node]][node] += minflow;
                    flow[node][father[node]] -= minflow;
                }
                ans += minflow;
            }
    }
    return ans;
}

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

    //freopen("in", "r", stdin);

    scanf("%i %i", &n, &m);
    for (int i = 1; i <= m; ++ i)
    {
        scanf("%i %i %i", &x, &y, &z);
        g[x].push_back(y);
        g[y].push_back(x);
        cap[x][y] = z;
    }
    source = 1;
    sink = n;

    printf("%i\n", get_maxflow());
}