Cod sursa(job #2658879)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 15 octombrie 2020 13:21:39
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f

using namespace std;

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

int N;
vector < vector < int > > C, G;

bool BFS(int source, int sink, vector < int >& parent) {
    fill(parent.begin(), parent.end(), -1);
    parent[source] = -2;
    queue < pair < int , int > > Q;
    Q.emplace(source, INF);
    vector < bool > viz(N + 1);
    viz[source] = true;
    while(!Q.empty()) {
        int curr = Q.front().first,
            flow = Q.front().second;
        Q.pop();
        for(int next : G[curr]) {
            if(parent[next] == -1 && C[curr][next] && !viz[next]) {
                viz[next] = true;
                parent[next] = curr;
                int new_flow = min(flow, C[curr][next]);
                if(next == sink)
                    return new_flow;
                Q.emplace(next, new_flow);
            }
        }
    }
    return 0;
}

int max_flow(int source, int sink) {
    int flow = 0, new_flow;
    vector < int > parent(N + 1);
    while(new_flow = BFS(source, sink, parent)) {
        flow += new_flow;
        int curr = sink;
        while(curr != source) {
            int prev = parent[curr];
            C[prev][curr] -= new_flow;
            C[curr][prev] += new_flow;
            curr = prev;
        }
    }
    return flow;
}

int main() {
    fin.sync_with_stdio(false);
    fout.sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr);
    int M;
    fin >> N >> M;
    C = vector < vector < int > >(N + 1, vector < int >(N + 1));
    G.resize(N + 1);
    while(M--) {
        int u, v, w;
        fin >> u >> v >> w;
        C[u][v] += w;
        G[u].emplace_back(v);
    }
    fout << max_flow(1, N);
}