Cod sursa(job #3377497)

Utilizator teobsnTeodor Bostan teobsn Data 23 noiembrie 2026 14:48:45
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e3;
vector<int> G[NMAX + 1];
int p[NMAX + 1], vis[NMAX + 1];
int capacitate[NMAX + 1][NMAX + 1];

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

int ek(int sursa, int destinatie, int n)
{
    for (int i = 1; i <= n; i++)
    {
        p[i] = 0;
        vis[i] = 0;
    }

    queue<int> q;
    q.push(sursa);
    vis[sursa] = 1;

    while (!q.empty())
    {
        int node = q.front();
        q.pop();

        for (int vec : G[node])
        {
            if (!vis[vec] && capacitate[node][vec] > 0)
            {
                vis[vec] = 1;
                p[vec] = node;
                if (vec == destinatie)
                    break;
                q.push(vec);
            }
        }
        if (vis[destinatie])
            break;
    }

    if (vis[destinatie] == 0)
        return 0;

    int flow = 1e9;
    int x = destinatie;
    while (x != sursa)
    {
        flow = min(flow, capacitate[p[x]][x]);
        x = p[x];
    }

    x = destinatie;
    while (x != sursa)
    {
        capacitate[p[x]][x] -= flow;
        capacitate[x][p[x]] += flow;
        x = p[x];
    }

    return flow;
}

int main()
{
    int n, m;
    fin >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;

        G[a].push_back(b);
        capacitate[a][b] += c;

        G[b].push_back(a);
    }

    int sum = 0;
    while (true)
    {
        int flux = ek(1, n, n);
        if (flux == 0)
            break;
        sum += flux;
    }

    fout << sum << "\n";
    return 0;
}