Cod sursa(job #2985291)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 26 februarie 2023 10:50:37
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;

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

const int MAX_N = 1005;
const int INF = 0x3f3f3f3f;
int n, m;

int graph[MAX_N][MAX_N];
int flow[MAX_N][MAX_N];
int father[MAX_N];
queue <int> q;

void InitQueue() {
    while (!q.empty()) {
        q.pop();
    }
    q.push(1); 
}

bool BFS() {
    InitQueue();
    memset(father, 0, sizeof(father));
    father[1] = 1;

    while (!q.empty()) {
        int node = q.back();
        q.pop();

        if (node == n) {
            return true;
        }

        for (int i = 1; i <= n; i++) {
            if (!father[i] && graph[node][i] - flow[node][i] > 0) {
                q.push(i);
                father[i] = node;
            }
        }
    }
    return false;
}

int GetMin() {
    int minVal = INF;

    int node = n;
    while (father[node] != node) {
        int parent = father[node];
        if (flow[parent][node] < minVal) {
            minVal = graph[parent][node] - flow[parent][node];
        }

        node = parent;
    }
    return minVal;
}

void UpdateFlow(int value) {
    int node = n;
    while (father[node] != node) {
        int parent = father[node];
        flow[parent][node] += value;
        flow[node][parent] -= value;
        node = parent;
    }
}

int main() {
    fin >> n >> m;

    for (int i = 0; i < m; i++) {
        int a, b, c;
        fin >> a >> b >> c;
        graph[a][b] = c;
        graph[b][a] = c;
        flow[b][a] = c;
    }

    while (BFS()) {
        int minVal = GetMin();
        UpdateFlow(minVal);
    }

    int ans = 0;
    for (int i = 1; i <= n; i++) {
        ans += flow[1][i];
    }

    fout << ans << '\n';

    return 0;
}