Author : Dipu Kumar Mohanto
CSE, Batch - 6
BRUR.
Problem Statement : Gomory Hu Tree Implementation
Source :
Category : Graph Theory
Algorithm : Gomory Hu Tree, All pair maximum flow
Complexity : O(n * T(maxflow))
Verdict : Ok.
This implementation is for undirected graph.
- #include <bits/stdc++.h>
-
- using namespace std;
-
- #define ll long long int
- #define inf 123456678890
-
- static const int maxn = 200 + 5;
-
- struct node
- {
- int v, w;
- node(int v = 0, int w = 0) : v(v), w(w) {}
- };
-
- vector <int> graph[maxn];
- vector <node> gomoryTree[maxn];
- int tnode, tedge;
- ll cap[maxn][maxn];
- ll flow[maxn][maxn];
- int level[maxn], ptr[maxn];
- int father[maxn];
- ll maxflow[maxn];
-
- bool bfs(int source, int sink)
- {
- fill(begin(level), end(level), -1);
- queue <int> PQ;
- PQ.push(source);
- level[source] = 0;
- while (!PQ.empty())
- {
- int u = PQ.front(); PQ.pop();
- for (int v : graph[u])
- {
- if (level[v] != -1 || flow[u][v] >= cap[u][v]) continue;
- level[v] = level[u] + 1;
- PQ.push(v);
- }
- }
- return level[sink] != -1;
- }
-
- ll dfs(int u, ll minCap, int sink)
- {
- if (u == sink) return minCap;
- for (int &i = ptr[u]; i < (int)graph[u].size(); i++)
- {
- int v = graph[u][i];
- if (level[v] == level[u]+1 && flow[u][v] < cap[u][v])
- {
- ll minFlow = dfs(v, min(minCap, cap[u][v] - flow[u][v]), sink);
- if (minFlow > 0)
- {
- flow[u][v] += minFlow;
- flow[v][u] -= minFlow;
- return minFlow;
- }
- }
- }
- return 0;
- }
-
- ll DinicMaxFlow(int source, int sink)
- {
- int maxFlow = 0;
- while(bfs(source, sink))
- {
- memset(ptr, 0, sizeof ptr);
- while(ll bottleneck = dfs(source, inf, sink))
- {
- maxFlow += bottleneck;
- }
- }
- return maxFlow;
- }
-
- void setCapacity(int u, int v, ll cost)
- {
- cap[u][v] = cost;
- cap[v][u] = cost;
- }
-
- void addEdge(int u, int v)
- {
- graph[u].push_back(v);
- graph[v].push_back(u);
- }
-
- void clearFlow()
- {
- for (int i = 0; i < maxn; i++)
- {
- for (int j = 0; j < maxn; j++)
- {
- flow[i][j] = flow[j][i] = 0;
- }
- }
- }
-
- int main()
- {
- freopen("in.txt", "r", stdin);
-
- cin >> tnode >> tedge;
- for (int e = 0; e < tedge; e++)
- {
- int u, v, w;
- cin >> u >> v >> w;
- u++, v++;
- cerr << u << " " << v << endl;
- addEdge(u, v);
- setCapacity(u, v, w);
- }
-
- for (int i = 1; i <= tnode; i++) father[i] = 1;
- for (int i = 2; i <= tnode; i++)
- {
- clearFlow();
- maxflow[i] = DinicMaxFlow(i, father[i]);
- bfs(i, father[i]);
- for (int j = i+1; j <= tnode; j++)
- {
- if (level[j] != -1 && father[j] == father[i]) father[j] = i;
- }
- }
-
- for (int i = 2; i <= tnode; i++)
- {
- gomoryTree[i].push_back(node(father[i], maxflow[i]));
- gomoryTree[ father[i] ].push_back(node(i, maxflow[i]));
- cout << i << " " << father[i] << " " << maxflow[i] << endl;
- }
-
- }
-
- 6 11
- 0 1 10
- 0 5 8
- 1 5 3
- 1 2 4
- 1 4 2
- 2 5 2
- 2 4 4
- 2 3 5
- 3 5 2
- 3 4 7
- 4 5 3
-
- 2 1 18
- 3 2 13
- 4 3 14
- 5 3 15
- 6 2 17
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.