Cod sursa(job #2568767)

Utilizator Fatu_SamuelFatu Samuel Fatu_Samuel Data 4 martie 2020 09:46:21
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <cstring>
#include <climits>
using namespace std;

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

const int NMAX = 1005;
const int MMAX = 5005;

queue<int> q;
vector<int> ad[NMAX];
int n, m, c[NMAX][NMAX], f[NMAX][NMAX], pred[NMAX];
int flow = 0;

void citire()
{
    int x, y, cst, i;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>cst;
        ad[x].push_back(y);
        ad[y].push_back(x);
        c[x][y] += cst;
    }
}

void EK(int x)
{
    memset(pred, 0xff, sizeof(pred));
    q.push(x);
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        for(int v : ad[x])
        {
            if(pred[v] == -1 && c[x][v] > f[x][v])
            {
                pred[v] = x;
                q.push(v);
            }
        }
    }

    int fmin = INT_MAX;
    for(x = n; x > 1; x = pred[x])
    {
        fmin = min(fmin, c[pred[x]][x] - f[pred[x]][x]);
    }
    for(x = n; x > 1; x = pred[x])
    {
        f[pred[x]][x] += fmin;
        f[x][pred[x]] -= fmin;
    }
    flow+=fmin;
}

int main()
{
    memset(pred, 0xff, sizeof(pred));

    citire();

    do
    {
        EK(1);
    }while(pred[n] != -1);

    fout<<flow;
    fin.close();
    fout.close();
    return 0;
}