Cod sursa(job #2954833)

Utilizator IRadu1529Radu Ionescu IRadu1529 Data 15 decembrie 2022 16:38:29
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;


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

#define N 1001

int n, m, maxFlow;
int s, t;
int capacity[N][N];
vector<vector<int>> l(N, vector<int>());
vector<int> parent(N);


int bfs(int s, int t) {
    parent[s] = -2; // ?
    queue<pair<int, int>> q;
    q.push({ s, 1e9 });

    while (!q.empty()) {
        int cur = q.front().first;
        int maxFlow = q.front().second;
        q.pop();

        for (int next : l[cur]) { 
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                int bottleneck = min(maxFlow, capacity[cur][next]);
                if (next == t)
                    return bottleneck;
                q.push({ next, bottleneck });
            }
        }
    }

    return 0;
}

void read() {
    fin >> n >> m;

    while (m--) {
        int a, b, c;
        fin >> a >> b >> c;
        l[a].push_back( b );
        l[b].push_back( a );
        capacity[a][b] += c; // muchia de inaintare 
    }
}

int main() {
    
    read();

    s = 1; t = n;

    for (int i = 1; i <= n; i++) // resetam parintii
        parent[i] = -1;

    int bottleneck;
    while (bottleneck = bfs(s, t)) { // cat mai sunt path uri care mai accepta flux
        maxFlow += bottleneck;
        int cur = t;
        while (cur != s) { // mergem inapoi pe path ul gasit 
            int prev = parent[cur];
            capacity[prev][cur] -= bottleneck; // muchia de inaintare
            capacity[cur][prev] += bottleneck;
            cur = prev;
        }

        for (int i = 1; i <= n; i++) // resetam parintii
            parent[i] = -1;
    }

    fout << maxFlow;
    
    return 0;
}