Cod sursa(job #2676903)

Utilizator LittleWhoFeraru Mihail LittleWho Data 25 noiembrie 2020 11:50:18
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 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;
vector<int> G[nmax];
int capacity[nmax][nmax];
int flow[nmax][nmax];
int parents[nmax];
bitset<nmax> visited;
int n, m;
int source, dest;

void read() {
    cin>>n>>m;
    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;
    }
    source = 1;
    dest = n;
}

void bfs() {
    queue<int> q;
    visited.reset();

    q.push(source);
    while (!q.empty()) {
        int cur_node = q.front();
        q.pop();

        for (auto next_node: G[cur_node]) {
            if (!visited[next_node] && flow[cur_node][next_node] < capacity[cur_node][next_node]) {
                parents[next_node] = cur_node;
                visited[next_node] = true;
                q.push(next_node);
            }
        }

        if (cur_node == dest) break;
    }
}

int maxflow = 0;
void update_path() {
    int node = dest;
    int minflow = INF;
    while (node != source) {
        minflow = min(capacity[parents[node]][node] - flow[parents[node]][node], minflow);
        node = parents[node];
    }

    node = dest;
    while (node != source) {
        flow[parents[node]][node] += minflow;
        flow[node][parents[node]] -= minflow;
        node = parents[node];
    }
    maxflow += minflow;
}

void solve() {    
    while (true) {
        bfs();
        if (visited[dest] == false) break;
        update_path();
    }
}

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

int main() {
    //freopen("input", "r", stdin);
    freopen("maxflow.in", "r", stdin); 
    freopen("maxflow.out", "w", stdout); 
      
    ios::sync_with_stdio(false);
    cin.tie(NULL);

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

    return 0;
}