Cod sursa(job #2961014)

Utilizator andriciucandreeaAndriciuc Andreea andriciucandreea Data 5 ianuarie 2023 16:06:01
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

int N, M;
vector <int> capacity[1005], adj[1005];

int BFS(int start, int end, vector<int>& parent)
{
    parent.resize(N + 1);
    fill(parent.begin(), parent.end(), -1);
    parent[start] = -2;
    queue <pair <int, int>> q;
    q.push({ start, INT_MAX });

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

        for (int next : adj[current])
        {
            if (parent[next] == -1 && capacity[current][next])
            {
                parent[next] = current;
                int new_flow = min(flow, capacity[current][next]);
                if (next == end)
                    return new_flow;
                q.push({ next, new_flow });
            }
        }
    }
    return 0;
}


int MaxFlow(int start, int end)
{
    int flow = 0;
    vector<int> parent(N);
    int new_flow;

    while (new_flow = BFS(start, end, parent))
    {
        flow += new_flow;
        int current = end;
        while (current != start)
        {
            int prev = parent[current];
            capacity[prev][current] -= new_flow;
            capacity[current][prev] += new_flow;
            current = prev;
        }
    }
    return flow;
}

int main()
{

    fin >> N >> M;
    int source = 1, dest = N;
    for (int i = 0; i <= N; i++)
    {
        adj[i].resize(N + 1);
        capacity[i].resize(N + 1);
    }
    for (int edge = 0; edge < M; edge++)
    {
        int x, y, cap;
        fin >> x >> y >> cap;
        capacity[x][y] = cap;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    int maxFlow = MaxFlow(source, dest);
    fout << maxFlow << endl;
}