Cod sursa(job #1736872)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 2 august 2016 20:22:51
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 flow;
    int capacity;

    int nod;
    int urm;
};

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

int tata[MAX_N];
int pointer[MAX_N];

int N, M;
int contor;

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

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

    queue<int> Q;
    tata[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 (!tata[son] && G[p].capacity > G[p].flow)
            {
                pointer[son] = p;
                tata[son] = node;

                if (son == T)
                    return true;

                Q.push(son);
            }
        }
    }

    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 (tata[son] != 0 && G[p ^ 1].capacity > G[p ^ 1].flow)
            {
                pointer[T] = p ^ 1;
                tata[T] = son;

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

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

                totalFlow += minFlow;
                node = T;

                while (node != S)
                {
                    G[ pointer[node] ].flow += minFlow;
                    G[ pointer[node] ^ 1 ].flow -= minFlow;
                    node = tata[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;
}