Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- vector<vector<int>> capacity; // storing the capacity of each edge
- vector<vector<int>> mat; // graph representation in adjacency matrix
- // utilizing Breadth First Search (BFS) algorithm
- int bfs(int s, int t, vector<int>& prev) {
- fill(prev.begin(), prev.end(), -1); // initalize previous nodes with -1
- prev[s] = -2;
- queue<pair<int, int>> q;
- q.push({s, INF});
- // while queue is not empty
- while (!q.empty()) {
- int cur = q.front().first;
- int flow = q.front().second;
- q.pop();
- for (int next : mat[cur]) {
- if (prev[next] == -1 && capacity[cur][next]) {
- prev[next] = cur;
- int new_flow = min(flow, capacity[cur][next]);
- if (next == t)
- return new_flow;
- q.push({next, new_flow});
- }
- }
- }
- return 0;
- }
- // computing maximum flow in the graph
- int maxflow(int s, int t) {
- int flow = 0;
- vector<int> prev(n);
- int new_flow;
- // doing BFS in each iteration, finding the shortest path available from 's' to 't'
- while (new_flow = bfs(s, t, prev)) {
- flow += new_flow;
- int cur = t;
- while (cur != s) {
- int prev = prev[cur];
- capacity[prev][cur] -= new_flow;
- capacity[cur][prev] += new_flow;
- cur = prev;
- }
- }
- return flow;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement