Cod sursa(job #3336997)

Utilizator floron1337Florin Venis floron1337 Data 26 ianuarie 2026 20:20:05
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

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

int capacity[NMAX][NMAX];
int parent[NMAX];
vector<int> G[NMAX];

int N, M;

int bfs(int s, int t)
{
    fill(parent, parent + N + 1, -1);

    parent[s] = 0;
    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 (auto neigh : G[node])
        {
            if (parent[neigh] == -1 && capacity[node][neigh] > 0)
            {
                int new_flow = min(flow, capacity[node][neigh]);
                parent[neigh] = node;

                if (neigh == t)
                    return new_flow;

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

int edmonds_karp(int s, int t)
{
    int max_flow = 0;
    int current_flow;

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

        int curr = t;

        while (curr != 0)
        {
            int next = parent[curr];

            capacity[next][curr] -= current_flow;
            capacity[curr][next] += current_flow;

            curr = next;
        }
    }

    return max_flow;
}

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

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

        capacity[x][y] += c;
    }

    int max_flow = edmonds_karp(1, N);
    fout << max_flow;

    return 0;
}