Cod sursa(job #3168792)

Utilizator LucaMuresanMuresan Luca Valentin LucaMuresan Data 13 noiembrie 2023 12:32:49
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
#include <queue>
#warning That's the baby, that's not my baby

typedef long long ll;

struct Dinic{
    struct Edge{
        int from, to, cap, ult;
    };
    std::vector <Edge> edges;
    std::vector <int> dist, last;
    std::queue <int> coada;
    int n;
    Dinic(int n){
        last.assign(n + 1, -1);
        this->n = n;
    }
    void baga(int from, int to, int cap){
        edges.push_back({from, to, cap, last[from]});
        last[from] = edges.size() - 1;
        edges.push_back({to, from, 0, last[to]});
        last[to] = 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(int y = last[x]; y != -1; y = edges[y].ult)
                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(int y = last[s]; y != -1; y = edges[y].ult)
            if(edges[y].cap > 0 && dist[edges[y].to] == dist[s] + 1)
            {
                int trimis = dfs(edges[y].to, t, std::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() {
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(0);
  std::cout.tie(0);

  #ifndef LOCAL
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
  #endif

  int n, m;
  std::cin >> n >> m;

  Dinic fm(n);

  for (int i = 0; i < m; i++) {
    int from, to, capacity;
    std::cin >> from >> to >> capacity;
    fm.baga(from, to, capacity);
  }
  std::cout << fm.fluxmax(1, n);

  return 0;
}