Cod sursa(job #2955929)

Utilizator StanCatalinStanCatalin StanCatalin Data 18 decembrie 2022 12:19:11
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>

using namespace std;

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

const int dim = 1005;

int n,m, sursa, destinatie;
vector<pair<int,pair<int,int>>> graf_rezidual[dim];
queue<int> q;
int tata[dim], dist[dim];

int BFS(vector<int> &vec) {
    for (int i=1; i<=n; i++) {
        dist[i] = 1e9;
    }
    tata[sursa] = 0;
    dist[sursa] = 0;
    q.push(sursa);

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

        for (auto y:graf_rezidual[x]) {
            if (y.second.first > 0 && dist[y.first] > dist[x] + 1) {
                dist[y.first] = dist[x] + 1;
                tata[y.first] = x;
                q.push(y.first);
            }
        }
    }

    if (dist[destinatie] == 1e9) return 0;

    int nod = destinatie;
    while (nod != 0) {
        vec.push_back(nod);
        nod = tata[nod];
    }
    reverse(vec.begin(), vec.end());
    return 1;
}

int main() {
    in >> n >> m;
    int x, y, c;
    sursa = 1;
    destinatie = n;
    while (m--) {
        in >> x >> y >> c;
        graf_rezidual[x].push_back({y, {c, 1}});
        graf_rezidual[y].push_back({x, {0, 0}});
    }
    int maxflow = 0;
    vector<int> lant;
    while (BFS(lant)) {

        int index = 1;
        int nod = sursa;
        int mini = 1e9;
        while (index < lant.size()) {
            for (auto y:graf_rezidual[nod]) {
                if (y.first == lant[index]) {
                    mini = min(mini, y.second.first);
                }
            }
            nod = lant[index];
            index++;
        }
        maxflow += mini;

        index = 1;
        nod = sursa;
        while (index < lant.size()) {
            for (auto &y:graf_rezidual[nod]) {
                if (y.first == lant[index]) {
                    if (y.second.second == 1) {
                        y.second.first -= mini;
                    } else {
                        y.second.first += mini;
                    }
                }
            }
            nod = lant[index];
            index++;
        }
        lant.clear();
    }

    out << maxflow;
    return 0;
}