Cod sursa(job #2957311)

Utilizator StanCatalinStanCatalin StanCatalin Data 22 decembrie 2022 12:05:38
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <algorithm>
#include <climits>

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];
pair<int, int> tata[dim];
int viz[dim];
vector<pair<int,long long int*>> in_destinatie;

int BFS() {
    queue<int> q;
    for (int i=1; i<=n; i++) {
        viz[i] = 0;
    }
    tata[sursa] = {0, 0};
    viz[sursa] = 1;
    q.push(sursa);

    while (!q.empty()) {
        int x = q.front();
        q.pop();
        ///  if (x == destinatie) continue;
        for (int i=0; i<graf_rezidual[x].size(); i++) {
            auto y = graf_rezidual[x][i];
            if (y.second.first > 0 && !viz[y.first]) {
                viz[y.first] = 1;
                tata[y.first] = {x, i};
                q.push(y.first);
            }
        }
    }

    return viz[destinatie];
}

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

        pair<int, int> nod = tata[destinatie];
        int catre = destinatie;
        long long int mini = LONG_LONG_MAX;
        while (nod.first != 0) {
            mini = min(mini, graf_rezidual[nod.first][nod.second].second.first);
            nod = tata[nod.first];
        }
        maxflow += mini;

        nod = tata[destinatie];
        while (nod.first != 0) {
            int poz = graf_rezidual[nod.first][nod.second].second.second;
            graf_rezidual[nod.first][nod.second].second.first -= mini;
            graf_rezidual[catre][poz].second.first += mini;
            catre = nod.first;
            nod = tata[nod.first];
        }
    }

    out << maxflow;
    return 0;
}