Cod sursa(job #2962711)

Utilizator witekIani Ispas witek Data 8 ianuarie 2023 23:18:00
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

int n, m;
vector <vector<int>> v, c;
vector <int> t;
vector <bool> visited;

void init() {
    v = vector <vector<int>> (n + 1);
    c = vector <vector<int>> (n + 1, vector <int> (n + 1));
    t = vector <int> (n + 1);
    visited = vector <bool> (n + 1);
}

void read() {
    fin >> n >> m;
    init();
    int x, y, cap;
    for(int i = 1; i <= m; i ++) {
        fin >> x >> y >> cap;
        v[x].push_back(y);
        v[y].push_back(x);
        c[x][y] = cap;
    }
}

bool bfs() {
    fill(visited.begin(), visited.end(), 0);
    queue <int> q;
    q.push(1);
    visited[1] = true;
    int node;
    while(!q.empty()) {
        node = q.front();
        q.pop();
        if(node == n)
            continue;
        for(const auto& neighbour : v[node]) {
            if(!visited[neighbour] && c[node][neighbour]) {
                t[neighbour] = node;
                visited[neighbour] = true;
                q.push(neighbour);
            }
        }
    }
    return visited[n];
}

int getMaxFlow() {
    int ansFlow = 0;
    while(bfs()) {
        for(const auto& neighbor : v[n]) {
            if(!visited[neighbor])
                continue;
            int minFlow = 2e9;
            t[n] = neighbor;
            for (int node = n; node != 1; node = t[node]) {
                if (c[t[node]][node] < minFlow)
                    minFlow = c[t[node]][node];
            }
            if(minFlow == 0)
                continue;
            ansFlow += minFlow;
            for (int node = n; node != 1; node = t[node]) {
                c[t[node]][node] -= minFlow;
                c[node][t[node]] += minFlow;
            }
        }
    }
    return ansFlow;
}

void dfs(int node) {
    visited[node] = true;
    for(const auto& neighbor : v[node])
        if(c[node][neighbor] && !visited[node])
            dfs(neighbor);
}

void mincut() {
    fill(visited.begin(), visited.end(), false);
    dfs(1);
    for(int i = 1; i <= n; i++)
        if(visited[i])
            for(const auto &neighbor : v[i])
                if(!visited[neighbor])
                    fout << i << " " << neighbor << '\n';
}

int main() {
    read();
    fout << getMaxFlow() << '\n';
    ///punctul b
    //mincut();
}

///Complexitate : O(N * M^2)