Dang_Quan_10_Tin

Dinic Phiên bản dễ nhìn hơn

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