Cod sursa(job #2658672)

Utilizator marius004scarlat marius marius004 Data 14 octombrie 2020 18:35:48
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("maxflow.in");
ofstream g("maxflow.out");

const int NMAX = 1'001;

int N, M, C[NMAX][NMAX], Flow[NMAX][NMAX], parent[NMAX];
vector < int > G[NMAX];

// C[x][y] - cat e capacitatea muchiei (x, y)
// Flux[x][y] - fluxul muchiei (x, y)
// t - vectorul de tati

bool bfs() {

    for(int i = 1;i <= N;++i) parent[i] = 0;

    vector < bool > vis(N + 1, false);
    queue < int > q;

    q.push(1);
    vis[1] = true;

    while(!q.empty()) {

        const int node = q.front();
        q.pop();

        for(const int& neighbour : G[node]) {

            if(!vis[neighbour] && C[node][neighbour] > Flow[node][neighbour]) {

                parent[neighbour] = node;
                q.push(neighbour);
                vis[neighbour] = true;

                if(neighbour == N)
                    return true;
            }
        }
    }

    return false;
}

int main() {

    f >> N >> M;

    while(M--) {

        int x, y, capacity;
        f >> x >> y >> capacity;

        // construim graful rezidual
        G[x].push_back(y);
        G[y].push_back(x);
        C[x][y] += capacity;
    }

    int sol{};
    while(bfs()) {

        int minnEdge{ (1 << 30) };

        int node = N;

        while(node != 1) {
            // (parent[node], node)
            minnEdge = min(minnEdge, C[ parent[node] ][node] - Flow[ parent[node] ][node]);
            node = parent[node];
        }

        node = N;
        while(node != 1) {
            // (parent[node], node)
            Flow[ parent[node] ][node] += minnEdge;
            Flow[ node ][ parent[node] ] -= minnEdge;
            node = parent[node];
        }

        sol += minnEdge;
    }

    g << sol;

    return 0;
}