Cod sursa(job #3159543)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 21 octombrie 2023 15:56:30
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;

struct Dinic{
    struct Edge{
        int from, to, cap;
    };
    vector <Edge> edges;
    vector <int> dist;
    vector <vector<int>> much;
    queue <int> coada;
    int n;
    Dinic(int n){
        much.resize(n + 1, {});
        this->n = n;
    }
    void baga(int from, int to, int cap){
        edges.push_back({from, to, cap});
        much[from].push_back(edges.size() - 1);
        edges.push_back({to, from, 0});
        much[to].push_back(edges.size() - 1);
    }
    bool bfs(int s, int t)
    {
        dist.assign(n + 1, 1e9);
        dist[s] = 0;
        coada.push(s);
        while(coada.size())
        {
            int x = coada.front();
            coada.pop();
            for(auto y:much[x])
                if(edges[y].cap > 0 && dist[edges[y].to] == 1e9)
                {
                    dist[edges[y].to] = dist[x] + 1;
                    coada.push(edges[y].to);
                }
        }
        return (dist[t] != 1e9);
    }
    int dfs(int s, int t, int flux)
    {
        if(s == t)
            return flux;
        int rez = 0;
        for(auto y:much[s])
            if(edges[y].cap > 0 && dist[edges[y].to] == dist[s] + 1)
            {
                int trimis = dfs(edges[y].to, t, min(flux, edges[y].cap));
                rez += trimis;
                flux -= trimis;
                edges[y].cap -= trimis;
                edges[y ^ 1].cap += trimis;
            }
        return rez;
    }
    int fluxmax(int s, int t)
    {
        int rez = 0;
        while(bfs(s, t))
            rez += dfs(s, t, 1e9);
        return rez;
    }
};

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    int n, m, from, to, cap;
    cin >> n >> m;
    Dinic g(n);
    for(int i = 1; i <= m; i++)
    {
        cin >> from >> to >> cap;
        g.baga(from, to, cap);
    }
    cout << g.fluxmax(1, n);
    return 0;
}