Cod sursa(job #3136719)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 7 iunie 2023 22:18:13
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include <bits/stdc++.h>
using namespace std;

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

/*
struct edge{
    int node;
    int cap;
    int flow;
    edge(int node, int cap, int flow) : node(node), cap(cap), flow(flow) {}
};
*/

unordered_map < int , bool > mp;
pair < int , int > flow[1005][1005];
vector < int > v[1005];
queue < int > q;
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);
        v[y].push_back(x);
    }
}

void bfs() {
    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; }
            }
        }
    }
}

void ford_fulk() {
    ok = 1;
    while (ok) {
        mp.clear();
        while (!q.empty()) q.pop();
        mp[source] = 1;
        q.push(source);
        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;
}