Advertisement
nasarouf

BPM/flow

Apr 9th, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. //usage: Flow<int> f(n); /*make graph using f.conn...*/ f.reserflow(); f.flow(0,1); f.f[][] wil have the flow values
  2.  
  3. #define MAX 404
  4.  
  5. template<class Node, class adjType, class fromType>
  6. bool bfs(Node a, Node b, const adjType &adj, function<bool(int, int)> rc, fromType &from) {
  7.     static Node q[MAX]; int qh = 0, qt = 0; q[qh++] = a;
  8.     static map<Node, int> visited; static int flag = 0;
  9.     visited[a] = ++flag;
  10.     while (qh > qt) {
  11.         a = q[qt++]; if (a == b) return true;
  12.         for (Node j : adj[a]) {
  13.             if (rc(a, j) && visited[j] != flag) {
  14.                 visited[j] = flag; q[qh++] = j; from[j] = a;
  15.                 if (j == b) return true;
  16.             }
  17.         }
  18.     }
  19.     return false;
  20. }
  21.  
  22. template<class T>
  23. class Flow {
  24. public:
  25.     int n;
  26.     vector<set<int>> adj;
  27.     vector<vector<T>> c, f;
  28.  
  29.     inline void connect(int a,int b,T cap) {adj[a].insert(b);adj[b].insert(a);c[a][b]=(cap);}
  30.     inline void disconnect(int a,int b) {adj[a].erase(b);adj[b].erase(a);c[a][b]=0;}
  31.     inline void conn(int a, int b) { connect(a, b, 1); }
  32.     inline T residual(int i, int j){ return (c[i][j] - f[i][j]); }
  33.  
  34.     Flow(int _n=0):n(_n),adj(n,set<int>()), c(n, vector<T>(n, (T)0)), f(n, vector<T>(n, (T)0)) {}
  35.     void resetflow() { for (int i = 0; i < n; i++) for (auto j : adj[i]) f[i][j] = 0; }
  36.     T flow(int src = 0, int sink = 1) {
  37.         vector<int> from(n,0);
  38.         const auto &cc = c, &ff = f;
  39.         while (bfs(src, sink, adj, [=,&cc,&ff](int i, int j) mutable {return ((cc[i][j] - ff[i][j]) > 0); }, from)){
  40.             for (int b = 1; b != 0; b = from[b]){ f[from[b]][b] += 1; f[b][from[b]] -= 1; }
  41.         }
  42.         T sm = 0; for (int i = 2; i < n; i++) sm += f[0][i];
  43.         return sm;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement