Cod sursa(job #1537223)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 27 noiembrie 2015 01:03:50
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 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 nod;
    int capacity;
    int urm;
};

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

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

int N, M;
int contor;

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

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

    tata[S] = S;

    int st = 0, dr = 1;
    coada[ ++st ] = S;

    while (st <= dr)
    {
        int node = coada[ st++ ];

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

            if (tata[v] == 0 && G[p].capacity > 0)
            {
                tata[v] = node;
                pointer[v] = p;

                coada[ ++dr ] = v;

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

    return false;
}

int EdmondsKarp(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].capacity > 0)
            {
                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);
                    node = tata[node];
                }

                if (minFlow == 0)
                    continue;

                node = T;

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

                flow += minFlow;
            }
        }
    }

    return flow;
}

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 x, y, c;
        in >> x >> y >> c;

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

    out << EdmondsKarp(1, N) << "\n";

    return 0;
}