Cod sursa(job #1388121)

Utilizator IonSebastianIon Sebastian IonSebastian Data 15 martie 2015 10:46:26
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <cstdio>
#include <queue>
#include <cstring>

using namespace std;

const int MAX_N = 1000, MAX_M = 5000, INF = MAX_M*110000;

FILE *in, *out;

int lst[MAX_N+1], urm[2*MAX_M+1], vf[2*MAX_M+1];
int nrg;
int c[MAX_N+1][MAX_N+1], f[MAX_N+1][MAX_N+1];

int m, n;

void add(int x, int y, int cap)
{
    nrg++;
    urm[nrg] = lst[x];
    vf[nrg] = y;
    c[x][y] = cap;
    lst[x] = nrg;
}

queue<int> q;

int t[MAX_N+1];

bool viz[MAX_N+1];

bool bfs()
{
    q.push(1);
    memset(viz, false, sizeof(viz));
    viz[1] = true;
    int x;
    int p;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        p = lst[x];
        if(x != n)
        {
            while(p != 0)
            {
                if(!viz[vf[p]] && (c[x][vf[p]]-f[x][vf[p]] > 0))
                {
                    viz[vf[p]] = true;
                    q.push(vf[p]);
                    t[vf[p]] = x;
                }
                p = urm[p];
            }
        }
    }
    return viz[n];
}

int fmin;

int minim(int a, int b)
{
    return (a<b)?a:b;
}

int main()
{
    in = fopen("maxflow.in", "r");
    out = fopen("maxflow.out", "w");
    int x, y, cap;
    fscanf(in, "%d%d", &n, &m);
    for(int i = 0; i < m; i++)
    {
        fscanf(in,"%d%d%d", &x, &y, &cap);
        add(x,y,cap);
        add(y,x,0);
    }

    int flow = 0;
    while(bfs() == true)
    {
        int p = lst[n];
        while(p != 0)
        {
            if(viz[vf[p]] && c[vf[p]][n] - f[vf[p]][n] > 0)
            {
                t[n] = vf[p];
                fmin = INF;
                for(int nod = n; nod != 1; nod = t[nod])
                    fmin = minim(fmin, c[t[nod]][nod]-f[t[nod]][nod]);
                if(fmin != 0)
                {
                    for(int nod = n; nod != 1; nod = t[nod])
                    {
                        f[t[nod]][nod] += fmin;
                        f[nod][t[nod]] -= fmin;
                    }
                }
                flow += fmin;
            }
            p = urm[p];
        }
    }
    fprintf(out, "%d", flow);
    fclose(in);
    fclose(out);
    return 0;
}