Cod sursa(job #2967761)

Utilizator N.B.Lnabil. N.B.L Data 20 ianuarie 2023 01:43:26
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb

#include <iostream>
#include <list>
#include <vector>
#include <fstream>

#define HURRY_UP ios_base::sync_with_stdio(0) , cin .tie(0) , cout.tie(0);
#define  ll long long

using namespace std;

typedef pair<int, int> iPair;


const int MAX = 1e4;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");


int cap[MAX][MAX];
int N,M;

int path[MAX];
int pathLength;
bool visited[MAX];

int getPath(int StartNode, int TargetNode, int curLen, int maxcap) {
    path[curLen] = StartNode;
    if (StartNode == TargetNode) {
        pathLength = curLen + 1;
        return maxcap;
    }

    int ret = 0;
    visited[StartNode] = true;

    for (int i = 0; i < M; i++) {
        if (visited[i] || cap[StartNode][i] <= 0) continue;

        ret = getPath(i, TargetNode, curLen + 1, min(maxcap, cap[StartNode][i]));

        if (ret > 0) break;    // We found a path with flow
    }
    return ret;
}

int maxFlow(int src, int sink) {
    int total_flow = 0;

    while (1) {
        memset(visited, 0, sizeof(visited));
        int newflow = getPath(src, sink, 0, INT_MAX);

        if (!newflow) break;    // once no more paths, STOP

        for (int i = 1; i < pathLength; i++) {
            int m = path[i - 1], n = path[i];

            cap[m][n] -= newflow;
            cap[n][m] += newflow;        // Add reversed edge
        }
        total_flow += newflow;
    }

    return total_flow;
}

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


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


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


    return 0;
}