Cod sursa(job #2549964)

Utilizator KappaClausUrsu Ianis Vlad KappaClaus Data 18 februarie 2020 10:08:10
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 1000 + 1;

vector<vector<int>> graph(N_MAX, vector<int>());
int N, M;

int CAPACITY[N_MAX][N_MAX], FLOW[N_MAX][N_MAX], PARENT[N_MAX];
bool VISITED[N_MAX];



bool BFS()
{
    fill(VISITED + 1, VISITED + N + 1, false);

    queue<int> node_queue;

    node_queue.push(1);

    VISITED[1] = true;

    while(node_queue.empty() == false)
    {
        int current_node = node_queue.front();

        node_queue.pop();

        if(current_node == N) continue;

        for(auto& next_node : graph[current_node])
        {
            if(VISITED[next_node] == true || CAPACITY[current_node][next_node] == FLOW[current_node][next_node]) continue;

            VISITED[next_node] = true;

            node_queue.push(next_node);

            PARENT[next_node] = current_node;
        }
    }

    return VISITED[N];
}


int main()
{
    ifstream fin{"maxflow.in"};
    ofstream fout{"maxflow.out"};

    fin >> N >> M;

    for(int i = 1; i <= M; ++i)
    {
        int x, y, c;

        fin >> x >> y >> c;

        CAPACITY[x][y] = c;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    int max_flow = 0;

    while(BFS())
    {
        for(auto& parent_N : graph[N])
        {
            if(CAPACITY[parent_N] == FLOW[parent_N] || VISITED[parent_N] == false) continue;

            PARENT[N] = parent_N;

            int min_flow = (1 << 30);

            for(int node = N; node != 1; node = PARENT[node])
                min_flow = min(min_flow, CAPACITY[PARENT[node]][node] - FLOW[PARENT[node]][node]);

            if(min_flow == 0) continue;

            for(int node = N; node != 1; node = PARENT[node])
            {
                FLOW[PARENT[node]][node] += min_flow;
                FLOW[node][PARENT[node]] -= min_flow;
            }

            max_flow += min_flow;
        }
    }

    fout << max_flow;
}