Cod sursa(job #3155913)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 10 octombrie 2023 10:24:50
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int max_size = 1e3 + 6, INF = 2e9 + 1;

vector <int> mc[max_size];
int cap[max_size][max_size], viz[max_size], t[max_size], n;

bool bfs ()
{
    for (int i = 1; i <= n; i++)
    {
        viz[i] = 0;
    }
    queue <int> q;
    viz[1] = 1;
    q.push(1);
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (auto f : mc[nod])
        {
            if (!viz[f] && cap[nod][f] > 0)
            {
                t[f] = nod;
                viz[f] = 1;
                if (f == n)
                {
                    return true;
                }
                q.push(f);
            }
        }
    }
    return false;
}

int main ()
{
    int m;
    in >> n >> m;
    while (m--)
    {
        int x, y, c;
        in >> x >> y >> c;
        mc[x].push_back(y);
        mc[y].push_back(x);
        cap[x][y] += c;
    }
    int flux = 0;
    while (bfs())
    {
        for (auto f : mc[n])
        {
            if (!viz[f] || cap[f][n] <= 0)
            {
                continue;
            }
            t[n] = f;
            int nod = n, mn = INF;
            while (nod != 1)
            {
                mn = min(mn, cap[t[nod]][nod]);
                nod = t[nod];
            }
            flux += mn;
            if (mn <= 0)
            {
                continue;
            }
            nod = n;
            while (nod != 1)
            {
                cap[t[nod]][nod] -= mn;
                cap[nod][t[nod]] += mn;
                nod = t[nod];
            }
        }
    }
    out << flux;
    in.close();
    out.close();
    return 0;
}