Advertisement
Dang_Quan_10_Tin

Dinic

Nov 8th, 2020 (edited)
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. struct Edge
  2. {
  3.     int u, v;
  4.     ll c;
  5.     Edge() {}
  6.     Edge(int u, int v, ll c)
  7.     {
  8.         this->u = u;
  9.         this->v = v;
  10.         this->c = c;
  11.     }
  12. };
  13.  
  14. struct Dinic
  15. {
  16.     const ll Inf = 1e17;
  17.     vector<vector<int>> adj;
  18.     vector<vector<int>::iterator> cur;
  19.     vector<Edge> s;
  20.     vector<int> h;
  21.     int sink, t;
  22.     int n;
  23.     Dinic(int n)
  24.     {
  25.         this->n = n;
  26.         adj.resize(n + 1);
  27.         h.resize(n + 1);
  28.         cur.resize(n + 1);
  29.         s.reserve(n);
  30.     }
  31.     void AddEdge(int u, int v, ll c)
  32.     {
  33.         s.emplace_back(u, v, c);
  34.         adj[u].push_back(s.size() - 1);
  35.         s.emplace_back(v, u, 0);
  36.         adj[v].push_back(s.size() - 1);
  37.     }
  38.     bool BFS()
  39.     {
  40.         fill(h.begin(), h.end(), n + 2);
  41.         queue<int> pq;
  42.         h[t] = 0;
  43.         pq.emplace(t);
  44.         while (pq.size())
  45.         {
  46.             int c = pq.front();
  47.             pq.pop();
  48.             for (auto i : adj[c])
  49.                 if (h[s[i ^ 1].u] == n + 2 && s[i ^ 1].c != 0)
  50.                 {
  51.                     h[s[i ^ 1].u] = h[c] + 1;
  52.                     if (s[i ^ 1].u == sink)
  53.                         return true;
  54.                     pq.emplace(s[i ^ 1].u);
  55.                 }
  56.         }
  57.         return false;
  58.     }
  59.     ll DFS(int v, ll flowin)
  60.     {
  61.         if (v == t)
  62.             return flowin;
  63.         ll flowout = 0;
  64.         for (; cur[v] != adj[v].end(); ++cur[v])
  65.         {
  66.             int i = *cur[v];
  67.             if (h[s[i].v] + 1 != h[v] || s[i].c == 0)
  68.                 continue;
  69.             ll q = DFS(s[i].v, min(flowin, s[i].c));
  70.             flowout += q;
  71.             if (flowin != Inf)
  72.                 flowin -= q;
  73.             s[i].c -= q;
  74.             s[i ^ 1].c += q;
  75.             if (flowin == 0)
  76.                 break;
  77.         }
  78.         return flowout;
  79.     }
  80.     void BlockFlow(ll &flow)
  81.     {
  82.         for (int i = 1; i <= n; ++i)
  83.             cur[i] = adj[i].begin();
  84.         flow += DFS(sink, Inf);
  85.     }
  86.     ll MaxFlow(int s, int t)
  87.     {
  88.         this->sink = s;
  89.         this->t = t;
  90.         ll flow = 0;
  91.         while (BFS())
  92.             BlockFlow(flow);
  93.         return flow;
  94.     }
  95. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement