Cod sursa(job #2928489)

Utilizator average_disappointmentManolache Sebastian average_disappointment Data 23 octombrie 2022 00:35:47
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#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)) {

        int u = sink;
        maxflow = INT_MAX;

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

        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);
}