Cod sursa(job #1937858)

Utilizator FragentisMihai Petru Fragentis Data 24 martie 2017 12:41:51
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

typedef int Integer;
constexpr Integer INTEGER_MAX = 0x7fffffff;

vector<int> g[1001];
int n, m;

Integer* capacity[1001];
Integer* flux[1001];
int p[1001];
queue<int> coada;

void getAugmentationPath()
{
    fill(p + 2, p + n + 1, -1);

    coada.push(1);
    p[1] = 0;

    while(coada.empty() == false)
    {
        int v = coada.front();
        coada.pop();

        for(auto u : g[v])
        {
            if(p[u] == -1 && capacity[v][u] > flux[v][u])
            {
                p[u] = v;
                coada.push(u);
            }
        }
    }
}

Integer FordFulkerson()
{
    Integer flux_max = 0;

    while(true)
    {
        getAugmentationPath();
        if(p[n] == -1)
            break;

        Integer flux_min = INTEGER_MAX;
        for(int v = n; v != 1; v = p[v])
            flux_min = min(flux_min, capacity[p[v]][v] - flux[p[v]][v]);
        flux_max += flux_min;

        for(int v = n; v != 1; v = p[v])
        {
            flux[p[v]][v] += flux_min;
            flux[v][p[v]] -= flux_min;
        }
    }

    return flux_max;
}

int main()
{
    fstream f("maxflow.in", ios::in);
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        capacity[i] = new Integer[n + 1];
        flux[i] = new Integer[n + 1];

        fill(capacity[i] + 1, capacity[i] + n + 1, 0);
        fill(flux[i] + 1, flux[i] + n + 1, 0);
    }

    for(int i = 0; i < m; ++i)
    {
        int x, y;
        Integer cap;
        f >> x >> y >> cap;
        g[x].push_back(y);
        g[y].push_back(x);
        capacity[x][y] = cap;
    }
    f.close();

    Integer flux_max = FordFulkerson();

    for(int i = 1; i <=n; ++i)
    {
        delete[] capacity[i];
        delete[] flux[i];
    }

    f.open("maxflow.out", ios::out);
    f << flux_max;

    return 0;
}