Cod sursa(job #1379939)

Utilizator teo.serbanescuTeo Serbanescu teo.serbanescu Data 6 martie 2015 20:33:40
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.11 kb
#include <fstream>
#include <vector>
#include <queue>
#include <string.h>

using namespace std;

fstream f("maxflow.in",ios::in);
fstream g("maxflow.out",ios::out);

const int nmax = 1005;
const int INF = 0x3f3f3f3f;

vector <int> a[nmax];

int n, m, viz[nmax], t[nmax], c[nmax][nmax], cost, flow, fmin, i, x, y;

void citire()
{
    f >> n >> m;
    for (i = 1; i <= m; i++)
    {
        f >> x >> y >> cost;
        c[x][y] = cost;
        a[x].push_back(y);
        a[y].push_back(x);
    }
}

int existadrum()
{
    queue <int> q;
    int nc;
    q.push(1);
    viz[1] = 1;
    t[1] = 1;
    while (!q.empty())
    {
        nc = q.front();
        q.pop();
        for (vector <int>::iterator it = a[nc].begin(); it != a[nc].end(); ++it)
            if ((c[nc][*it] != 0) && (!viz[*it]))
            {
                if (*it != n)
                {
                    q.push(*it);
                    t[*it] = nc;
                }
                viz[*it] = 1;
            }
    }
    return viz[n];
}

void rezolvare()
{
    int xx, yy, nc;
    while (existadrum())
    {
        for (vector <int>::iterator it = a[n].begin(); it != a[n].end(); ++it)
            if ((c[*it][n] != 0) && (viz[*it]))
            {
                nc = *it;
                t[n] = nc;
                fmin = INF;
                nc = n;
                while (nc != 1)
                {
                    xx = t[nc]; yy = nc;
                    if (c[xx][yy] < fmin) fmin = c[xx][yy];
                    nc = t[nc];
                }
                flow += fmin;
                nc = n;
                if (fmin > 0)
                {
                    while (nc != 1)
                    {
                        xx = t[nc]; yy = nc;
                        c[xx][yy] -= fmin;
                        c[yy][xx] += fmin;
                        nc = t[nc];
                    }
                }
            }
        memset(viz, 0, sizeof(viz));
        memset(t, 0, sizeof(viz));
    }
}

int main()
{
    citire();
    rezolvare();
    g << flow;
    return 0;
}