Cod sursa(job #2928492)

Utilizator average_disappointmentManolache Sebastian average_disappointment Data 23 octombrie 2022 00:54:01
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include <fstream>
#include <cstring>
#include <climits>
#include <queue>
#include <vector>

using namespace std;

ifstream cin("maxflow.in");
ofstream cout("maxflow.out");

const int nmax = 1000, mmax = 5000;
int n, m, path[nmax + 1], capacity[nmax + 1][nmax + 1], flow[nmax + 1][nmax + 1];
vector<int> edges[nmax + 1];

bool Bfs(int source, int sink) {

    queue<int> q;
    q.push(source);

    while (!q.empty()) {

        int v = q.front();
        q.pop();

        for (int i = 0; i < edges[v].size(); i++) {

            int u = edges[v][i];
            if (capacity[v][u] > flow[v][u] && path[u] == 0) {

                path[u] = v;

                if (u == sink)
                    return true;

                q.push(u);
            }
        }
    }

    return false;
}

int EdmondsKarp(int source, int sink) {

    int ans_flow = 0, maxflow;
    while (Bfs(source, sink)) {

        for (int i = 0; i < edges[sink].size(); i++) {

            int u = edges[sink][i];

            if (capacity[u][sink] == flow[u][sink] || !path[u])
                continue;

            maxflow = INT_MAX;

            for (int uwu = sink; uwu != source; uwu = path[uwu])
                maxflow = min(maxflow, capacity[path[uwu]][uwu] - flow[path[uwu]][uwu]);

            if (!maxflow)
                continue;

            u = sink;
            while (u != source) {

                int v = path[u];
                flow[v][u] = flow[v][u] + maxflow;
                flow[u][v] = flow[u][v] - maxflow;

                u = v;
            }

            ans_flow += maxflow;
        }

        memset(path, 0, sizeof(path));
    }

    return ans_flow;
}

int main() {

    cin >> n >> m;
    for (int i = 1; i <= m; i++) {

        int x, y, z;
        cin >> x >> y >> z;

        capacity[x][y] = z;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }

    cout << EdmondsKarp(1, n);
}