Cod sursa(job #2698211)

Utilizator LittleWhoFeraru Mihail LittleWho Data 21 ianuarie 2021 14:09:28
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef signed long long ll;
typedef unsigned int uint;
typedef unsigned char uchar;
template <typename T>
void printarray(T v[], uint n) {for(uint i = 0; i < n; i ++){cout << v[i] << " ";}cout << endl;}
template <typename T>
void printvector(vector<T> v){for (uint i = 0; i < v.size(); i ++){cout << v[i] << " ";}cout << endl;}
#define dbg(x) cout << #x " = " << x << " | ";
#define dbgnl(x) cout << #x " = " << x << endl;

const int nmax = 1005;
const int INF = 2e9;
list<int> G[nmax];
int capacity[nmax][nmax];
int flow[nmax][nmax];
bitset<nmax> visited;
int parent[nmax];
int n, m;
int source, dest;
int maxflow = 0;

void read() {
    cin >> n >> m;
    source = 1;
    dest = n;
    for (int i = 0; i < m; ++i) {
        int x, y, c;
        cin >> x >> y >> c;
        G[x].push_back(y);
        G[y].push_back(x);
        capacity[x][y] = c;
    }
}

int update_path(int node, int residual) {
    int minflow = residual;
    int cur_node = node;
    while (cur_node != source) {
        minflow = min(minflow,  capacity[parent[cur_node]][cur_node] - flow[parent[cur_node]][cur_node]);
        cur_node = parent[cur_node];
    }

    cur_node = node;
    while (cur_node != source) {
        flow[parent[cur_node]][cur_node] += minflow;
        flow[cur_node][parent[cur_node]] -= minflow;
        cur_node = parent[cur_node];
    }

    return minflow;
}

bool update_flow() {
    queue<int> q;
    q.push(source);
    visited[source] = true;

    while (!q.empty()) {
        int node = q.front();
        q.pop();

        for (auto neighbour: G[node]) {
            if (!visited[neighbour] && flow[node][neighbour] < capacity[node][neighbour]) {
                visited[neighbour] = true;
                parent[neighbour] = node;
                q.push(neighbour);
            }
        }
    }

    if (visited[dest] == false) return false;

    for (auto sink: G[dest]) {
        if (flow[sink][dest] < capacity[sink][dest]) {
            int minflow = update_path(sink, capacity[sink][dest] - flow[sink][dest]);
            flow[sink][dest] += minflow;
            flow[dest][sink] -= minflow;
            maxflow += minflow;
        }
    }

    return true;
}

void solve() {
    while (update_flow()) {
        visited.reset();
    }
}

void write() {
    cout << maxflow << "\n";
}

int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    read();
    solve();
    write();

    return 0;
}