Cod sursa(job #2387994)

Utilizator EclipseTepes Alexandru Eclipse Data 25 martie 2019 16:07:15
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.14 kb
#include <iostream>
#include <fstream>
#include <deque>
#include <cstring>
#include <vector>

using namespace std;

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

const int dmax = 1e3 + 5;
const int INF = 1e9;

int n, m;
int x, y, z;
int ResGraph[dmax][dmax];
int parent[dmax];
int newV, pVerif, newFlow;
bool newPath, viz[dmax];
int maxFlow;
deque<int> d;

vector<int> graph[dmax];

bool BFS() {
    int i, j;
    memset(viz, false, sizeof(viz));
    memset(parent, false, sizeof(viz));
    viz[1] = true;
    newPath = false;
    d.push_back(1);
    while (!d.empty()) {
        pVerif = d.front();
        d.pop_front();
        for (i = 0; i < graph[pVerif].size(); i++) {
            newV = graph[pVerif][i];
            if (ResGraph[pVerif][newV] && !viz[newV]) {
                viz[newV] = true;
                if (newV == n) {
                    newPath = true;
                    continue;
                }
                d.push_back(newV);
                parent[newV] = pVerif;
            }
        }
    }
    return newPath;
}

void FindMinFlow() {
    int i, j;
    newFlow = INF;
    pVerif = n;
    while (pVerif != 1) {
        newFlow = min(newFlow, ResGraph[parent[pVerif]][pVerif]);
        pVerif = parent[pVerif];
    }
}

void AugmentPath() {
    int i, j;
    pVerif = n;
    while (pVerif != 1) {
        ResGraph[parent[pVerif]][pVerif] -= newFlow;
        ResGraph[pVerif][parent[pVerif]] += newFlow;
        pVerif = parent[pVerif];
    }
    maxFlow += newFlow;
}

void FordFulkerson() {
    int i, j;
    while (BFS()) {
        for (i = 0; i < graph[n].size(); i++) {
            newV = graph[n][i];
            if (ResGraph[newV][n] && viz[newV]) {
                parent[n] = newV;
                FindMinFlow();
                AugmentPath();
            }
        }
    }
}

int main() {
    int i, j;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> z;
        graph[x].push_back(y);
        graph[y].push_back(x);
        ResGraph[x][y] += z;
    }
    FordFulkerson();
    fout << maxFlow;
    return 0;
}