Cod sursa(job #2209050)

Utilizator vladboss2323Ciorica Vlad vladboss2323 Data 1 iunie 2018 16:41:05
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

const int N=1005;
const int INF=2000000000;
vector <int> a[N];

int n,m,s=1,d,vmin,flux;
bool viz[N];
int c[N][N],q[2*N],f[N][N],pred[N];

void citire()
{
    int x,y,z,i;
    in>>n>>m;
    d=n;
    for(i=1;i<=m;i++)
    {
        in>>x>>y>>z;
        a[x].push_back(y);
        c[x][y]=z;
    }
}

bool bfs()
{
    int x, y, st = 0, dr = -1;
    for (x = 1; x <= n; x++)
    {
        viz[x] = false;
    }
    q[++dr] = s;
    viz[s] = true;
    while (st <= dr)
    {
        x = q[st++];
        for (y = 1; y <= n; y++)
        {
            if (!viz[y] && c[x][y] > f[x][y])
            {
                q[++dr] = y;
                viz[y] = true;
                pred[y] = x;
                if (y == d)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

int drum_minim()
{
    int x = d, vmin = INF;
    while (x != s)
    {
        vmin = min(vmin, c[pred[x]][x] - f[pred[x]][x]);
        x = pred[x];
    }
    return vmin;
}

void actualizare_drum(int vmin)
{
    int x = d;
    while (x != s)
    {
        f[pred[x]][x] += vmin;
        f[x][pred[x]] -= vmin;
        x = pred[x];
    }
}

int main()
{
    citire();
    while (bfs())
    {
        vmin = drum_minim();
        flux += vmin;
        actualizare_drum(vmin);
    }
    out<<flux;
    return 0;
}