Cod sursa(job #2872827)

Utilizator florinrafiliuRafiliu Florin florinrafiliu Data 17 martie 2022 21:11:51
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

using namespace std;

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

const int maxN = 1005;
const int INF = 1e18;

int parent[maxN], a[maxN][maxN];

vector <int> g[maxN];

int bfs (int source, int sink) {

    for(int i = source; i <= sink; ++i)
        parent[i] = 0;

    queue <pair<int,int>> q;

    parent[source] = -1;
    q.push({source, INF});

    while(!q.empty()) {
        int node = q.front().first;
        int flow = q.front().second;

        q.pop();

        for(int to : g[node])
            if(parent[to] == 0 && a[node][to] > 0) {
                int newFlow = min(flow, a[node][to]);

                parent[to] = node;

                if(to == sink)
                    return newFlow;

                q.push({to, newFlow});
            }
    }

    return 0;
}

int maxFlow (int source, int sink) {

    int flow = 0, newFlow = 0;

    while(newFlow = bfs(source, sink)) {
        flow += newFlow;

        int to = sink;
        while(to != source) {
            int node = parent[to];

            a[node][to] -= newFlow;
            a[to][node] += newFlow;

            to = node;
        }
    }

    return flow;
}

signed main() {

    int n, m; fin >> n >> m;

    for(int i = 1; i <= m; ++i) {
        int u, v, c; fin >> u >> v >> c;

        g[u].push_back(v);
        g[v].push_back(u);

        a[u][v] += c;
    }

    int flow = maxFlow(1, n);

    fout << flow;

    return 0;
}