Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //usage: Flow<int> f(n); /*make graph using f.conn...*/ f.reserflow(); f.flow(0,1); f.f[][] wil have the flow values
- #define MAX 404
- template<class Node, class adjType, class fromType>
- bool bfs(Node a, Node b, const adjType &adj, function<bool(int, int)> rc, fromType &from) {
- static Node q[MAX]; int qh = 0, qt = 0; q[qh++] = a;
- static map<Node, int> visited; static int flag = 0;
- visited[a] = ++flag;
- while (qh > qt) {
- a = q[qt++]; if (a == b) return true;
- for (Node j : adj[a]) {
- if (rc(a, j) && visited[j] != flag) {
- visited[j] = flag; q[qh++] = j; from[j] = a;
- if (j == b) return true;
- }
- }
- }
- return false;
- }
- template<class T>
- class Flow {
- public:
- int n;
- vector<set<int>> adj;
- vector<vector<T>> c, f;
- inline void connect(int a,int b,T cap) {adj[a].insert(b);adj[b].insert(a);c[a][b]=(cap);}
- inline void disconnect(int a,int b) {adj[a].erase(b);adj[b].erase(a);c[a][b]=0;}
- inline void conn(int a, int b) { connect(a, b, 1); }
- inline T residual(int i, int j){ return (c[i][j] - f[i][j]); }
- Flow(int _n=0):n(_n),adj(n,set<int>()), c(n, vector<T>(n, (T)0)), f(n, vector<T>(n, (T)0)) {}
- void resetflow() { for (int i = 0; i < n; i++) for (auto j : adj[i]) f[i][j] = 0; }
- T flow(int src = 0, int sink = 1) {
- vector<int> from(n,0);
- const auto &cc = c, &ff = f;
- while (bfs(src, sink, adj, [=,&cc,&ff](int i, int j) mutable {return ((cc[i][j] - ff[i][j]) > 0); }, from)){
- for (int b = 1; b != 0; b = from[b]){ f[from[b]][b] += 1; f[b][from[b]] -= 1; }
- }
- T sm = 0; for (int i = 2; i < n; i++) sm += f[0][i];
- return sm;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement