Cod sursa(job #1739992)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 10 august 2016 17:16:36
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <bits/stdc++.h>

using namespace std;

constexpr int MAX_N = 1000 + 1;
constexpr int MAX_M = 5000 + 1;
constexpr int NIL = -1;

struct Edge
{
    int capacity;
    int flow;

    int nod;
    int urm;
};

Edge G[2 * MAX_M];
int head[MAX_N];

int father[MAX_N];
int pointer[MAX_N];

int N, M;
int contor;

void addEdge(int a, int b, int c)
{
    G[contor] = {c, 0, b, head[a]};
    head[a] = contor++;
}

bool BFS(int S, int T)
{
    for (int i = 1; i <= N; ++i)
    {
        pointer[i] = 0;
        father[i] = 0;
    }

    queue<int> Q;

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

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

        for (int p = head[node]; p != NIL; p = G[p].urm)
        {
            int son = G[p].nod;

            if (!father[son] && G[p].capacity > G[p].flow)
            {
                father[son] = node;
                pointer[son] = p;

                Q.push(son);

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

    return false;
}

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

    while (BFS(S, T))
    {
        for (int p = head[T]; p != NIL; p = G[p].urm)
        {
            int son = G[p].nod;

            if (father[son] != 0 && G[p ^ 1].capacity > G[p ^ 1].flow)
            {
                father[T] = son;
                pointer[T] = p ^ 1;

                int node = T;
                int fmin = numeric_limits<int>::max() / 2;

                while (node != S)
                {
                    fmin = min(fmin, G[ pointer[node] ].capacity - G[ pointer[node] ].flow);
                    node = father[node];
                }

                totalFlow += fmin;
                node = T;

                while (node != S)
                {
                    G[ pointer[node] ].flow += fmin;
                    G[ pointer[node] ^ 1 ].flow -= fmin;
                    node = father[node];
                }
            }
        }
    }

    return totalFlow;
}

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

    in >> N >> M;

    for (int i = 1; i <= N; ++i)
        head[i] = NIL;

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

        addEdge(a, b, c);
        addEdge(b, a, 0);
    }

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

    return 0;
}