Cod sursa(job #1684516)

Utilizator crysstyanIacob Paul Cristian crysstyan Data 11 aprilie 2016 09:30:09
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define NMAX 1005
#define inf 2000000000

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int i, n, m, x, y, z, cost[NMAX][NMAX], flow[NMAX][NMAX], father[NMAX], ans = 0;
bool visited[NMAX];
vector < int > v[NMAX];
queue < int > q;

bool BFS()
{
    for (int i = 1; i <= n; ++ i)
        visited[i] = 0;
    visited[1] = 1;
    q.push(1);
    father[1] = 0;

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

        for (auto & it : v[node])
            if (!visited[it] && flow[node][it] != cost[node][it])
        {
            visited[it] = 1;
            q.push(it);
            father[it] = node;
        }
    }

    return visited[n];
}

int main()
{
    f >> n >> m;

    for (i = 1; i <= m; ++ i)
    {
        f >> x >> y >> z;

        v[x].push_back(y);
        v[y].push_back(x);
        cost[x][y] = z;
    }

    while (BFS())
    {
        for (int j = 0; j < v[n].size(); ++ j)
        {
            int node = v[n][j];

            if (flow[node][n] == cost[node][n] || !visited[node])
                continue;

            father[n] = node;
            int minflow = inf;

            int curr = n;

            while (curr != 1)
            {
                minflow = min(minflow, cost[father[curr]][curr] - flow[father[curr]][curr]);
                curr = father[curr];
            }

            if (minflow == 0)
                continue;

            curr = n;

            while (curr != 1)
            {
                flow[father[curr]][curr] += minflow;
                flow[curr][father[curr]] -= minflow;
                curr = father[curr];
            }
            ans += minflow;
        }
    }

    g << ans << '\n';

    return 0;
}