Cod sursa(job #3336304)

Utilizator floron1337Florin Venis floron1337 Data 24 ianuarie 2026 15:30:53
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

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

const int NMAX = 505;
const int INF = 1e9;

int capacity[NMAX][NMAX];
int parent[NMAX];

int N, M;

int bfs(int s, int t)
{
    fill(parent, parent + N + 1, -1);
    parent[s] = -2;

    queue<pair<int, int>> q;
    q.push({s, INF});

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

        for (int i = 1; i <= N; i++)
        {
            if (capacity[node][i] > 0 && parent[i] == -1)
            {
                parent[i] = node;

                int new_flow = min(flow, capacity[node][i]);

                if (i == t)
                {
                    return new_flow;
                }

                q.push({i, new_flow});
            }
        }
    }
    return 0;
}

int max_flow(int s, int t)
{
    int max_flow = 0;
    int path_flow;

    while ((path_flow = bfs(s, t)))
    {
        max_flow += path_flow;

        int curr = t;

        while (curr != s)
        {
            int prev = parent[curr];

            capacity[curr][prev] += path_flow;
            capacity[prev][curr] -= path_flow;

            curr = prev;
        }
    }
    return max_flow;
}

int main()
{
    fin >> N >> M;

    for (int i = 0; i < M; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        capacity[x][y] += c;
    }

    fout << max_flow(1, N);

    return 0;
}