Cod sursa(job #604604)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 23 iulie 2011 16:36:39
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <iostream>
#include <vector>
#include <queue>

#define NMax 1005
#define Inf 2000000000

using namespace std;

vector <int> G[NMax];
int N, Cap[NMax][NMax], Flow[NMax][NMax], Father[NMax];
bool Viz[NMax];

void Read ()
{
    freopen ("maxflow.in", "r", stdin);
    int M;
    scanf ("%d %d", &N, &M);
    for (; M>0; --M)
    {
        int X, Y;
        scanf ("%d %d", &X, &Y);
        G[X].push_back (Y);
        G[Y].push_back (X);
        scanf ("%d", &Cap[X][Y]);
    }
}

inline int Min (int a, int b)
{
    if (a<b)
    {
        return a;
    }
    return b;
}

bool BFS (int Start, int Finish)
{
    queue <int> Q;
    for (int i=1; i<=N; ++i)
    {
        Viz[i]=false;
    }
    Q.push (Start);
    while (!Q.empty ())
    {
        int X=Q.front ();
        Q.pop ();
        Viz[X]=true;
        if (X==Finish)
        {
            continue;
        }
        for (unsigned v=0; v<G[X].size (); ++v)
        {
            int V=G[X][v];
            if (!Viz[V] and Cap[X][V]-Flow[X][V]>0)
            {
                Father[V]=X;
                Viz[V]=true;
                Q.push (V);
            }
        }
    }
    if (Viz[Finish])
    {
        return true;
    }
    return false;
}

int EdmondsKarp (int S, int D)
{
    int MaxFlow=0;
    while (BFS (S, D))
    {
        for (unsigned v=0; v<G[D].size (); ++v)
        {
            int V=G[D][v];
            if (!Viz[V] or Cap[V][D]-Flow[V][D]<=0)
            {
                continue;
            }
            int CurrentFlow=Inf;
            Father[D]=V;
            for (int X=D; X>1; X=Father[X])
            {
                CurrentFlow=Min (CurrentFlow, Cap[Father[X]][X]-Flow[Father[X]][X]);
            }
            for (int X=D; X>0; X=Father[X])
            {
                Flow[Father[X]][X]+=CurrentFlow;
                Flow[X][Father[X]]-=CurrentFlow;
            }
            MaxFlow+=CurrentFlow;
        }
    }
    return MaxFlow;
}

void Print ()
{
    freopen ("maxflow.out", "w", stdout);
    printf ("%d\n", EdmondsKarp (1, N));
}

int main()
{
    Read ();
    Print ();
    return 0;
}