Cod sursa(job #3136724)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 7 iunie 2023 22:50:39
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <iostream>
#include <unordered_map>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;

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

unordered_map < int, bool > mp;
pair < int, int > flow[1005][1005];
vector < int > v[1005], inv[1005];
int path[1005], n_path;
int parent[1005];

int max_flow;
int n, m, x, y;
int source, sink;
bool ok;

void read() {
    f >> n >> m;
    source = 1; sink = n;
    for (int i = 1;i <= m;i++) {
        f >> x >> y;
        f >> flow[x][y].second;
        v[x].push_back(y);
        inv[y].push_back(x);
    }
}

void bfs() {
    queue < int > q;
    q.push(source);
    mp[source] = 1;
    while (!q.empty() && !ok) {
        int nod = q.front();
        q.pop();
        for (int i : v[nod]) {
            if (flow[nod][i].second != flow[nod][i].first && !mp[i]) {
                q.push(i);
                mp[i] = true;
                parent[i] = nod;
                if (i == sink) { ok = 1; break; }
            }
        }
        for (int i : inv[nod]) {
            if (flow[nod][i].second != flow[nod][i].first && !mp[i]) {
                q.push(i);
                mp[i] = true;
                parent[i] = nod;
                if (i == sink) { ok = 1; break; }
            }
        }
    }
}

void ford_fulk() {
    ok = 1;
    while (ok) {
        mp.clear();
        ok = 0;
        bfs();
        if (ok) {
            int bottleneck = INT_MAX;
            int end_node = sink;
            while (end_node != source) {
                bottleneck = min(bottleneck, flow[parent[end_node]][end_node].second - flow[parent[end_node]][end_node].first);
                end_node = parent[end_node];
            }
            end_node = sink;
            while (end_node != source) {
                flow[parent[end_node]][end_node].first += bottleneck;
                flow[end_node][parent[end_node]].first -= bottleneck;
                end_node = parent[end_node];
            }
            max_flow += bottleneck;
        }
    }
}

int main()
{
    read();
    ford_fulk();
    g << max_flow;
    return 0;
}