Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- vector<int> level, edge_begin;
- vector<vector<edge>> edges;
- // Simple BFS calculating distance of each vertex from the source
- bool level_bfs(int s, int t)
- {
- fill(level.begin(), level.end(), -1);
- level[s] = 0;
- queue<int> Q;
- Q.push(s);
- while (!Q.empty())
- {
- int from = Q.front();
- Q.pop();
- for (edge& e : edges[from])
- if (level[e.to] < 0 && e.flow < e.capacity)
- {
- level[e.to] = level[from] + 1;
- Q.push(e.to);
- }
- }
- // Return true if the target is reachable from the source
- return level[t] != -1;
- }
- // Recursion to push flow from a parent vertex to the target
- int push_flow(int from, int t, int flow)
- {
- if (from == t)
- return flow;
- // Iterate untraversed edges to find a subpath to the target with positive capacity
- for (; edge_begin[from] < edges[from].size(); edge_begin[from]++)
- {
- edge& e = edges[from][edge_begin[from]];
- // Ascertain foward motion and sufficient capcity
- if (level[e.to] == level[from] + 1 && e.flow < e.capacity)
- {
- int subpath_flow = push_flow(e.to, t, min(flow, e.capacity - e.flow));
- // Update the flow with the positive capacity subpath, if such has been found
- if (subpath_flow > 0)
- {
- e.flow += subpath_flow;
- edges[e.to][e.rev].flow -= subpath_flow;
- return subpath_flow;
- }
- }
- }
- // No positive capacity subpath found
- return 0;
- }
- // Find the maximum flow of a directed graph
- int Dinic(int s, int t)
- {
- // Assumes source can't be the target
- int result = 0;
- // Keep pushing flows until unable to reach the target from the source
- while (level_bfs(s, t))
- {
- // Reset current edge iteration for all vertexes
- fill(edge_begin.begin(), edge_begin.end(), 0);
- while (int flow = push_flow(s, t, INT_MAX))
- result += flow;
- }
- return result;
- }
Add Comment
Please, Sign In to add comment