Cod sursa(job #2954820)

Utilizator IRadu1529Radu Ionescu IRadu1529 Data 15 decembrie 2022 15:56:07
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <fstream>
#include <cmath>
#include <math.h>
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];
int flow[N][N];
vector<vector<int>> l(N, vector<int>());
vector<int> parent(N);


int bfs(int s, int t) {

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

    parent[s] = -2; // orice != -1 sau [1,n]s
    queue<pair<int, int>> q;
    q.push({ s, INT_MAX });

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

        for (int next : l[node]) {
            if (parent[next] == -1 && capacity[node][next] != flow[node][next]) {
                parent[next] = node;
                int bottleneck = min(maxFlow, capacity[node][next] - flow[node][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
        capacity[b][a] = 0; // muchia de intoarcere (intial nu se poate face undo deoarece nu trece nimic)
    }
}

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];
            //cout << prev << " " << cur << "\n";
            flow[prev][cur] += bottleneck; // muchia de inaintare
            flow[cur][prev] -= bottleneck;
            cur = prev;
        }
        //cout << "\n\n";
    }

    fout << maxFlow;
    
    return 0;
}