Cod sursa(job #2881976)

Utilizator Edyci123Bicu Codrut Eduard Edyci123 Data 31 martie 2022 03:49:07
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <bits/stdc++.h>
#define DIM 1005
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

int n, m, flow, c[DIM][DIM], t[DIM];
bitset <DIM> viz;
queue <int> q;
vector <int> edges[DIM];

void init()
{
    viz.reset();
    for (int i = 1; i <= n; i++)
        t[i] = i;
    viz[1] = 1;
    q.push(1);
}

bool bfs()
{
    init();
    bool reachedDest = false;
    while (!q.empty())
    {
        int node = q.front();
        q.pop();

        for (auto child : edges[node])
            if (!viz[child] && c[node][child] > 0)
            {
                viz[child] = 1;
                t[child] = node;
                q.push(child);
                if (child == n)
                    reachedDest = true;
            }
    }

    return reachedDest;
}

int main()
{
    f >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int x, y, capacity;
        f >> x >> y >> capacity;
        edges[x].push_back(y);
        edges[y].push_back(x);
        c[x][y] = capacity;
    }

    while (bfs())
    {
        for (auto child : edges[n])
            if (viz[child] && c[child][n])
            {
                int minim = INF, last = n;
                t[n] = child;

                int actual = n;
                while (actual != 1)
                {
                    minim = min(c[t[actual]][actual], minim);
                    actual = t[actual];
                }

                flow += minim;

                actual = n;
                while (actual != 1)
                {
                    c[t[actual]][actual] -= minim;
                    c[actual][t[actual]] += minim;
                    actual = t[actual];
                }
            }
    }

    g << flow;

    return 0;
}