Cod sursa(job #2224785)

Utilizator EclipseTepes Alexandru Eclipse Data 25 iulie 2018 09:21:22
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.16 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#include <string.h>
#define dMAX (1 << 10)
#define INF  (1 << 30)

using namespace std;

int n, m;
int x, y, c;
int maxFlow, augmentation;

vector<int> graf[dMAX + 2];

pair<int, int> trueGraph[dMAX + 2][dMAX + 2];
int residualGraph[dMAX + 2][dMAX + 2];
int father[dMAX + 2];

deque<int> myDeque;
bool viz[dMAX + 2];
int pVerif, newV, u;

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

bool BFS() {
    memset(viz, false, sizeof(viz));
    viz[1] = true;
    myDeque.clear();
    myDeque.push_back(1);
    while (!myDeque.empty()) {
        pVerif = myDeque.front();
        myDeque.pop_front();
        for (u = 0; u < graf[pVerif].size(); u++) {
            newV = graf[pVerif][u];
            if (viz[newV]) continue;
            if (trueGraph[pVerif][newV].first == trueGraph[pVerif][newV].second) continue;
            viz[newV] = true;
            myDeque.push_back(newV);
            father[newV] = pVerif;
            if (newV == n) return true;
        }
    }
    return false;
}

int main()
{
    int i, j;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        graf[x].push_back(y);
        graf[y].push_back(x);
        residualGraph[x][y] = c;
        trueGraph[x][y].second = c;
    }

    maxFlow = 0;
    while (BFS()) {
        for (i = 0; i < graf[n].size(); i++) {
            augmentation = INF;
            pVerif = graf[n][i];
            if (!viz[pVerif]) continue;
            if (trueGraph[pVerif][n].first == trueGraph[pVerif][n].second) continue;
            father[n] = pVerif;
            for (j = n; j != 1; j = father[j]) {
                augmentation = min(augmentation, trueGraph[father[j]][j].second - trueGraph[father[j]][j].first);
            }
            if (!augmentation) continue;
            for (j = n; j != 1; j = father[j]) {
                trueGraph[father[j]][j].first += augmentation;
                trueGraph[j][father[j]].first -= augmentation;
            }
            maxFlow += augmentation;
        }
    }

    fout << maxFlow;

    return 0;
}