Cod sursa(job #2773767)

Utilizator Stefan4814Voicila Stefan Stefan4814 Data 8 septembrie 2021 16:44:05
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define NMAX 1001

using namespace std;

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

int capacity[NMAX][NMAX], flow[NMAX][NMAX];
int dist[NMAX];
vector<int> graph[NMAX];

bool bfs (int source, int destination, int n) {
    for(int i = 1; i <= n; i++)
        dist[i] = INT_MAX;

    dist[source] = 0;
    queue<int> q;
    q.push(source);
    while(q.size()) {
        int node = q.front();
        q.pop();
        for(auto x : graph[node]) {
            if(capacity[node][x] > flow[node][x] and dist[x] > dist[node] + 1) {
                dist[x] = dist[node] + 1;
                q.push(x);
            }
        }
    }
    return dist[destination] != INT_MAX;
}

int best_flow(int node, int destination, int max_flow) {
    if(!max_flow)
        return 0;
    if(node == destination)
        return max_flow;
    int total = 0;
    for(auto x : graph[node]) {
        if(dist[x] == dist[node] + 1) {
            int curr_flow = best_flow(x, destination, min(max_flow - total, capacity[node][x] - flow[node][x]));
            flow[node][x] += curr_flow;
            flow[x][node] -= curr_flow;
            total += curr_flow;
        }
    }
    return total;
}


int main() {
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, weight;
        fin >> x >> y >> weight;
        graph[x].push_back(y);
        graph[y].push_back(x);
        capacity[x][y] += weight;
    }

    int total = 0, inf = INT_MAX;
    while(bfs(1, n, n))
        total += best_flow(1, n, inf);

    fout << total;
}