Cod sursa(job #2961911)

Utilizator crivoicarlaCrivoi Carla crivoicarla Data 7 ianuarie 2023 13:13:55
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
//
// Created by Carla on 1/7/2023.
//
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

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

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

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




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



int getMaxFlow() {
    int ansFlow = 0;
    while(bfs()) {
        int minFlow = 2e9;
        for (int node = n; node != 1; node = t[node]) {
            if (c[t[node]][node] < minFlow)
                minFlow = c[t[node]][node];
        }

        ansFlow += minFlow;
        for (int node = n; node != 1; node = t[node]) {
            c[t[node]][node] -= minFlow;
            c[node][t[node]] += minFlow;
        }
    }
    return ansFlow;
}



int main() {

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

    fout << getMaxFlow();

}