Cod sursa(job #2544082)

Utilizator bgunevBlago Ivov Gunev bgunev Data 11 februarie 2020 19:17:24
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
#include<fstream>
using namespace std;

const int MAX_N = 1024;
const int INF = 987654321;

int n, m;
int s, t;
int u, v, c;

struct edg
{
    int to;
    int capacity;
    int r;
};

vector<edg> sys[MAX_N];

int par[MAX_N];
int minC[MAX_N];
int edgeInd[MAX_N];

int ans;

int bfs()
{
    memset(par, -1, sizeof(par));
    memset(edgeInd, -1, sizeof(edgeInd));
    fill(minC, minC+n, INF);

    par[s] = 0;

    queue<int> q;
    q.push(s);

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

        if(curr == t){
            break;
        }

        for(int i = 0; i < sys[curr].size(); i++){
            if(sys[curr][i].capacity != 0 && par[sys[curr][i].to] == -1){
                int next = sys[curr][i].to;
                par[next] = curr;
                minC[next] = min(minC[curr], sys[curr][i].capacity);
                edgeInd[next] = i;
                q.push(next);
                //cout << next << " " << minC[next] << endl;
            }
        }

    }

    if(par[t] == -1){
        return 0;
    }

    int curr = t;
    int change = minC[t];

    while(curr != s){
        int p = par[curr];
        sys[p][edgeInd[curr]].capacity -= change;
        sys[curr][sys[p][edgeInd[curr]].r].capacity += change;
        curr = p;
    }

    return change;

}

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    #define cin myFileIn
    ifstream myFileIn;
    myFileIn.open("maxflow.in");

    #define cout myFileOut
    ofstream myFileOut;
    myFileOut.open("maxflow.out");

    cin >> n >> m;
    s = 0;
    t = n-1;

    for(int i = 0; i < m; i++){
        cin >> u >> v >> c;
        u--; v--;
        sys[u].push_back({v, c, sys[v].size()});
        sys[v].push_back({u, 0, sys[u].size()-1});
    }

    int add = bfs();
    while(add != 0){
        ans += add;
        add = bfs();
    }

    cout << ans << endl;


return 0;
}