Cod sursa(job #2576523)

Utilizator danhHarangus Dan danh Data 6 martie 2020 20:10:06
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;

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

const int N = 1005;

vector<int> v[N];
int f[N][N], c[N][N], pred[N];
int n, m;

queue<int> q;

int flux;

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 : v[x])
        {
            if(pred[el] == -1 && c[x][el] > f[x][el])
            {
                pred[el] = x;
                q.push(el);
            }
        }
    }

    if(pred[n] != -1)
    {
        for(int el : v[n])
        {
            int fmin = 0x3f3f3f3f;
            if(pred[el] != -1 && c[el][n] > f[el][n])
            {
                pred[n] = el;
                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;
                }
                flux += fmin;
            }
        }
    }
}

int main()
{
    int i, j, x, y, cap;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y>>cap;
        v[x].push_back(y);
        v[y].push_back(x);
        c[x][y] += cap;
    }

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

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