Cod sursa(job #2700479)

Utilizator rapidu36Victor Manz rapidu36 Data 27 ianuarie 2021 20:33:09
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.17 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N = 1001;
const int M = 10000;
const int INF = 1 << 30;

struct muchie
{
    int x, y, c, f;
};

int n, nr, nivel[N], poz[N];
vector <int> a[N];
queue <int> q;
muchie v[M];

void adauga_muchie(int x, int y, int c)
{
    v[nr] = (muchie){x, y, c, 0};
    a[x].push_back(nr++);
    v[nr] = (muchie){y, x, 0, 0};//muchia de intoarcere
    a[y].push_back(nr++);
}

void init_nivel()
{
    for (int i = 2; i <= n; i++)
    {
        nivel[i] = -1;
    }
}

void init_poz()
{
    for (int i = 1; i <= n; i++)
    {
        poz[i] = 0;
    }
}

bool bfs()
{
    init_nivel();
    q.push(1);
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (auto i: a[x])
        {
            int y = v[i].y, c = v[i].c, f = v[i].f;
            if (c == f) continue;
            if (nivel[y] != -1) continue;
            nivel[y] = 1 + nivel[x];
            q.push(y);
        }
    }
    return (nivel[n] != -1);
}

int dfs(int x, int valf)
{
    if (x == n)
    {
        return valf;
    }
    while (poz[x] < (int)a[x].size())
    {
        int i = a[x][poz[x]];
        int y = v[i].y;
        int c = v[i].c;
        int f = v[i].f;
        if (nivel[y] != 1 + nivel[x] || f == c)
        {
            poz[x]++;
            continue;
        }
        int f_curent = dfs(y, min(valf, c - f));
        if (f_curent != 0)
        {
            v[i].f += f_curent;
            v[i ^ 1].f -= f_curent;
            return f_curent;
        }
        poz[x]++;
    }
    return 0;
}

int flux()
{
    int f = 0;
    while (bfs())
    {
        int f_curent;
        init_poz();
        while ((f_curent = dfs(1, INF)) != 0)
        {
            f += f_curent;
        }
    }
    return f;
}

int main()
{
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");
    int m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y, c;
        in >> x >> y >> c;
        adauga_muchie(x, y, c);
    }
    in.close();
    out << flux();
    out.close();
    return 0;
}