Cod sursa(job #1736792)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 2 august 2016 16:57:40
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;

constexpr int MAX_N = 1000 + 1;

int flow[MAX_N][MAX_N];
int tata[MAX_N];
vector<int> G[MAX_N];

int N, M;

bool bfs(int S, int T)
{
    for (int i = 1; i <= N; ++i)
        tata[i] = 0;

    queue<int> Q;

    tata[S] = S;
    Q.push(S);

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

        for (int v : G[node])
        {
            if (!tata[v] && flow[node][v] > 0)
            {
                tata[v] = node;
                Q.push(v);

                if (v == T)
                    return true;
            }
        }
    }

    return false;
}

int maxFlow(int S, int T)
{
    int totalFlow = 0;

    while (bfs(S, T))
    {
        for (int v : G[T])
        {
            if (!tata[v] || flow[v][T] <= 0)
                continue;

            tata[T] = v;

            int node = T;
            int mflow = numeric_limits<int>::max();

            while (node != S)
            {
                mflow = min(mflow, flow[ tata[node] ][node]);
                node = tata[node];
            }

            if (!mflow)
                continue;

            totalFlow += mflow;

            node = T;

            while (node != S)
            {
                flow[ tata[node] ][node] -= mflow;
                flow[node][ tata[node] ] += mflow;
                node = tata[node];
            }
        }
    }

    return totalFlow;
}

int main()
{
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");

    in >> N >> M;

    for (int i = 1; i <= M; ++i)
    {
        int a, b, c;
        in >> a >> b >> c;

        G[a].push_back(b);
        G[b].push_back(a);

        flow[a][b] += c;
        flow[b][a] -= c;
    }

    out << maxFlow(1, N) << endl;

    return 0;
}