Cod sursa(job #2955944)

Utilizator StanCatalinStanCatalin StanCatalin Data 18 decembrie 2022 12:39:30
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>
#include <limits.h>

using namespace std;

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

const int dim = 1005;

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

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

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

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

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

    pair<int,int> nod = {destinatie, -1};
    while (nod.first != 0) {
        vec.push_back(nod.second);
        nod = tata[nod.first];
    }
    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}});
    }
    long long int maxflow = 0;
    vector<int> lant;
    while (BFS(lant)) {
        int index = 0;
        int nod = sursa;
        long long int mini = LONG_LONG_MAX;
        while (index < lant.size() - 1) {
            mini = min(mini, graf_rezidual[nod][lant[index]].second.first);
            nod = graf_rezidual[nod][lant[index]].first;
            index++;
        }
        maxflow += mini;

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

    out << maxflow;
    return 0;
}