Cod sursa(job #2556621)

Utilizator catalintermureTermure Catalin catalintermure Data 25 februarie 2020 08:25:39
Problema Flux maxim Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>
#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

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

const int NMAX = 1000;

vector<int> ad[NMAX];
int flow[NMAX][NMAX];
int cap[NMAX][NMAX];
int pred[NMAX];

int main() {
    int n, m, x, y, c;
    inf >> n >> m;
    for(int i = 0; i < m; i++) {
        inf >> x >> y >> c;
        x--;
        y--;
        cap[x][y] += c;
        if(!cap[y][x]) {
            ad[x].push_back(y);
            ad[y].push_back(x);
        }
    }
    int ftot = 0;
    do {
        memset(pred, 0xff, sizeof(pred));
        queue<int> q;
        q.push(0);
        while(!q.empty()) {
            x = q.front();
            q.pop();
            for(int el : ad[x]) {
                if(pred[el] == -1 && flow[x][el] < cap[x][el] && el != 0) {
                    pred[el] = x;
                    q.push(el);
                }
            }
        }

        if(pred[n - 1] != -1) {
            int fmin = 0x3f3f3f3f;
            for(int x = pred[n - 1]; pred[x] != -1; x = pred[x]) {
                fmin = min(fmin, cap[pred[x]][x] - flow[pred[x]][x]);
            }
            for(int x = pred[n - 1]; pred[x] != -1; x = pred[x]) {
                flow[pred[x]][x] += fmin;
                flow[x][pred[x]] -= fmin;
            }
            ftot += fmin;
        }

    } while(pred[n - 1] != -1);

    outf << ftot;
    return 0;
}