Cod sursa(job #2562066)

Utilizator rusu.ralucaRusu Raluca rusu.raluca Data 29 februarie 2020 11:57:45
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <bitset>
#include <queue>

using namespace std;

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

const int MAXN = 1005;
const int MAXM = 5005;
const int oo = 0x3f3f3f3f;

int n, m, x, y, z;
vector<int> g[MAXN];
int c[MAXN][MAXN], father[MAXN];
bitset <MAXN> used;
queue <int> q;

inline bool bfs(int source, int target){
    used.reset();
    used[source] = 1;
    q.push(source);
    while(!q.empty()){
        int node = q.front();
        q.pop();
        if(node == target)
            continue;
        for(auto it : g[node]){
            if(!used[it] && c[node][it] > 0){
                used[it] = 1;
                father[it] = node;
                q.push(it);
            }
        }
    }
    return used[target];
}

int getmaxFlow(int source, int target){
    int maxflow = 0;
    int bottleneck = 0x3f3f3f3f;

    while(bfs(source,target)){
        for(auto it : g[target]){

            if(!used[it] || c[it][target] <= 0)
                continue;

            int bottleneck = 0x3f3f3f3f;
            father[target] = it;

            for(int i = target ; i != source ; i = father[i])
                bottleneck = min(bottleneck, c[father[i]][i]);

            if(!bottleneck)
                continue;

            for(int i = target ; i != source ; i = father[i]) {
                c[father[i]][i] -= bottleneck;
                c[i][father[i]] += bottleneck;
            }

          maxflow += bottleneck;
        }
    }
    return maxflow;
}

int main(){
    in >> n >> m;
    for(int i = 1; i <= m; ++i){
        in >> x >> y >>z;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
    }  

    out << getmaxFlow(1, n) << '\n';
    
    return 0;
}