Cod sursa(job #2961079)

Utilizator andriciucandreeaAndriciuc Andreea andriciucandreea Data 5 ianuarie 2023 19:00:15
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <climits>

using namespace std;

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

int N, M;
vector <vector<int>> capacity, adj;
vector <bool> vis;
vector <int> parent;

int BFS(int start, int end)
{
    parent.resize(N + 5);
    vis.resize(N + 5);
    fill(parent.begin(), parent.end(), -1);
    fill(vis.begin(), vis.end(), false);
    //parent[start] = -2;
    vis[start] = true;
    queue <int> q;
    q.push(start);

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

        if (current == end)
            continue;

        for (int next : adj[current])
        {
            if (!vis[next] && capacity[current][next])
            {
                vis[next] = true;
                parent[next] = current;
                q.push(next);
            }
        }
    }
    return vis[end];
}


int MaxFlow(int start, int end)
{
    int max_flow = 0;
    
    while (BFS(start, end))
    {
        for (int x : adj[end])
        {
            if (vis[x] && capacity[x][end])
            {
                parent[end] = x;
                int flow = INT_MAX;

                for (int node = end; node != start; node = parent[node])
                    flow = min(flow, capacity[parent[node]][node]);

                for (int node = end; node != start; node = parent[node])
                {
                    capacity[parent[node]][node] -= flow;
                    capacity[node][parent[node]] += flow;
                }

                max_flow += flow;
            }
        }
    }

    return max_flow;
}

int main()
{

    fin >> N >> M;
    int source = 1, dest = N;
    adj.resize(N + 5);
    capacity.resize(N + 5);
    for (auto& line : capacity)
        line.resize(N + 5, 0);
    for (auto& line : adj)
        line.resize(N + 5, 0);
    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;
}