Cod sursa(job #1454126)

Utilizator geniucosOncescu Costin geniucos Data 25 iunie 2015 15:00:27
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#include<cstdio>
#include<vector>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<map>
#include<set>
#include<queue>
#include<algorithm>

using namespace std;

int INF, S, D, N_flow, M, left[100009], right[100009], C_F[100009], t[100009];
vector < int > v[100009];

void add_edge (int x, int y, int cap)
{
    left[++M] = x, right[M] = y, C_F[M] = cap, v[x].push_back (M);
    left[++M] = y, right[M] = x, C_F[M] = 0, v[y].push_back (M);
}

int opus (int pos)
{
    if (pos & 1)
        return pos + 1;
    return pos - 1;
}

bool bfs ()
{
    queue < int > cc;
    for (int i=1; i<=N_flow; i++)
        t[i] = -1;
    t[S] = 0;
    cc.push (S);
    while (!cc.empty ())
    {
        int nod = cc.front ();
        cc.pop ();
        for (vector < int > :: iterator it = v[nod].begin (); it != v[nod].end (); it ++)
            if (C_F[*it] > 0 && t[right[*it]] == -1)
            {
                t[right[*it]] = *it;
                if (right[*it] == D)
                    return 1;
                cc.push (right[*it]);
            }
    }
    return 0;
}

int Max_Flow ()
{
    int sol = 0;
    while (bfs ())
    {
        for (vector < int > :: iterator it = v[D].begin (); it != v[D].end (); it ++)
            if (C_F[opus(*it)] > 0 && t[right[*it]] != -1)
            {
                int mini = INF;
                t[D] = opus (*it);
                for (int i=D; i != S; i = left[t[i]])
                    if (C_F[t[i]] < mini)
                        mini = C_F[t[i]];
                sol += mini;
                for (int i=D; i != S; i = left[t[i]])
                {
                    C_F[t[i]] -= mini;
                    C_F[opus (t[i])] += mini;
                }
            }
    }
    return sol;
}

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

INF = 1<<30;
int M_init = 0;
scanf ("%d %d", &N_flow, &M_init), S = 1, D = N_flow;
while (M_init)
{
    M_init --;
    int x, y, z;
    scanf ("%d %d %d", &x, &y, &z);
    add_edge (x, y, z);
}
printf ("%d\n", Max_Flow ());

return 0;
}