Cod sursa(job #2569371)

Utilizator danhHarangus Dan danh Data 4 martie 2020 11:56:43
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

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

const int N = 1005;
const int M = 5005;
int n, m, flux;
int c[N][N], pred[N], f[N][N];

vector<int> ad[N];

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

queue<int>q;

void EK(int x)
{
    memset(pred, 0xff, sizeof(pred));
    q.push(x);
    while(!q.empty())
    {
        x = q.front();
        q.pop();

        if(x == n)
        {
            continue;
        }
        for(int el : ad[x])
        {
            if(pred[el] == -1 && c[x][el] > f[x][el])
            {
                pred[el] = x;
                q.push(el);
            }
        }
    }
    if(pred[n] != -1)
    {
        for(int el : ad[n])
        {
            int fmin = 0x3f3f3f3f;

                pred[n] = el;

                for(x = n; x != 1; x = pred[x])
                {
                    int tt = pred[x];
                    fmin = min(fmin, c[tt][x] - f[tt][x]);
                }
                for(x=n; x != 1; x= pred[x])
                {
                    int tt = pred[x];
                    f[tt][x] += fmin;
                    f[x][tt] -= fmin;
                }
                flux += fmin;

        }
    }
}


int main()
{
    citire();

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

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