Cod sursa(job #1538397)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 28 noiembrie 2015 22:45:09
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 1000 + 1;
const int MAX_M = 5000 + 1;
const 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;
    Q.push(S);
    tata[S] = S;

    while (Q.empty() == false)
    {
        int nod = Q.front();
        Q.pop();

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

            if (tata[son] == 0 && flow < capacity)
            {
                tata[son] = nod;
                pointer[son] = p;

                if (son == T)
                    return true;

                Q.push(son);
            }
        }
    }

    return false;
}

int flux(int S, int T)
{
    int flow = 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].flow < G[p ^ 1].capacity)
            {
                tata[T] = son;
                pointer[T] = p ^ 1;

                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];
                }

                flow += minFlow;

                node = T;

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

    return flow;
}

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

    scanf("%d%d", &N, &M);

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

    while (M--)
    {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);

        addEdge(x, y, c);
        addEdge(y, x, 0);
    }

    printf("%d\n", flux(1, N));

    return 0;
}