ec1117

Untitled

Nov 27th, 2020 (edited)
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. /**
  2.  * Description: Fast flow. After computing flow, edges $\{u,v\}$ such that
  3.     * $lev[u] \neq -1,$ $lev[v] = -1$ are part of min cut.
  4.     * Use \texttt{reset} and \texttt{rcap} for Gomory-Hu.
  5.  * Time: $O(N^2M)$ flow, $O(M\sqrt N)$ bipartite matching
  6.  * Source: GeeksForGeeks, Chilli
  7.  * Verification: RMI 2017 Day 1 Fashion
  8.     * https://pastebin.com/VJxTvEg1
  9.  */
  10.  
  11. DINIC
  12.  
  13. template<int SZ> struct Dinic {
  14.     int N,s,t; // # verts, source, sink
  15.     typedef ll F; // flow type
  16.     struct Edge { int to, rev; F flo, cap; };
  17.     vector<Edge> adj[SZ]; // use asserts, don't be dumb
  18.     void reset() { F0R(i,N) trav(e,adj[i]) e.flo = 0; }
  19.     void ae(int u, int v, F cap, F rcap = 0) {
  20.         assert(min(cap,rcap) >= 0);
  21.         Edge a{v,sz(adj[v]),0,cap}, b{u,sz(adj[u]),0,rcap};
  22.         adj[u].pb(a), adj[v].pb(b); }
  23.     int lev[SZ]; typename vector<Edge>::iterator cur[SZ];
  24.     bool bfs() { // level = shortest distance from source
  25.         F0R(i,N) lev[i] = -1, cur[i] = begin(adj[i]);
  26.         queue<int> q({s}); lev[s] = 0;
  27.         while (sz(q)) {
  28.             int u = q.ft; q.pop();
  29.             trav(e,adj[u]) if (lev[e.to] < 0 && e.flo < e.cap)
  30.                 q.push(e.to), lev[e.to] = lev[u]+1;
  31.         }
  32.         return lev[t] >= 0;
  33.     }
  34.     F dfs(int v, F flo) {
  35.         if (v == t) return flo;
  36.         for (; cur[v] != end(adj[v]); cur[v]++) {
  37.             Edge& e = *cur[v];
  38.             if (lev[e.to]!=lev[v]+1||e.flo==e.cap) continue;
  39.             F df = dfs(e.to,min(flo,e.cap-e.flo));
  40.             if (df) { e.flo += df; adj[e.to][e.rev].flo -= df;
  41.                 return df; } // saturated >=1 one edge
  42.         }
  43.         return 0;
  44.     }
  45.     F maxFlow(int _N, int _s, int _t) {
  46.         N = _N, s = _s, t = _t; assert(s != t);
  47.         F tot = 0; while (bfs()) while (F df =
  48.             dfs(s,numeric_limits<F>::max())) tot += df;
  49.         return tot;
  50.     }
  51. };
Add Comment
Please, Sign In to add comment