Cod sursa(job #2967764)

Utilizator N.B.Lnabil. N.B.L Data 20 ianuarie 2023 01:52:19
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <bits/stdc++.h>
//#include "/usr/local/include/bits/stdc++.h"
// ALGORITMUL EDMONDS-KARP O(V * E^2)


using namespace std;

const int MAX = 1e6;
#define  ll long long
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

vector<vector<int>> capacitate;

int path[MAX];
bool vizitat[MAX];

int M, N;
ll pathLength;


// DFS, BFS, DIJKSTRA
int getPath(int startNode, int targetNode, int curLen, int maxCap) {
    path[curLen] = startNode;

    if (startNode == targetNode) {
        pathLength = curLen + 1;
        return maxCap;
    }

    int res = 0;
    vizitat[startNode] = true;

    for (int i = 0; i < N; ++i) {
        if (vizitat[i] || capacitate[startNode][i] <= 0) continue;
        res = getPath(i, targetNode, curLen + 1, min(maxCap, capacitate[startNode][i]));
        if (res > 0) break;
    }

    return res;
}

ll maxFlow(int startNode, int endNode) {
    ll totalFlow = 0;

    while (true) {
        memset(vizitat, false, sizeof (vizitat));
        int newFlow = getPath(startNode, endNode, 0, INT_MAX);

        if (newFlow <= 0)break; // once there is no paths anymore stop the algo

        for (int i = 1; i < pathLength; ++i) {
            int m = path[i - 1];
            int n = path[i];
            capacitate[m][n] -= newFlow;
            capacitate[n][m] += newFlow;
        }
        totalFlow += newFlow;
    }

    return totalFlow;
}

//4 5
//1 2 3
//1 3 5
//2 4 6
//3 4 4
//3 2 3
int main() {

    fin >> N >> M;
    capacitate.resize(N+1,vector<int>(M));

    for (int i = 0; i < M; ++i) {
        int x, y, z;
        fin >> x >> y >> z;
        capacitate[x][y]= z;
    }
    fout << maxFlow(1, N);

//    cin >> N >> M;
//    capacitate.resize(N+1,vector<int>(M));
//
//    for (int i = 0; i < M; ++i) {
//        int x, y, z;
//        cin >> x >> y >> z;
//        capacitate[x][y]= z;
//    }
//    cout << maxFlow(1, N);



    return 0;
}