summaryrefslogtreecommitdiff
path: root/maxFlow/edmondsKarp.cpp
blob: ccfb1d22e6d2423c4f752ea1cb568a5c1d324ac6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int s, t, f; //source, target, single flow
int res[MAX_V][MAX_V]; //adj-matrix
vector< vector<int> > adjList;
int p[MAX_V]; //bfs spanning tree

void augment(int v, int minEdge) {
	if (v == s) { f = minEdge; return; }
	else if (p[v] != -1) {
		augment(p[v], min(minEdge, res[p[v]][v]));
		res[p[v]][v] -= f; res[v][p[v]] += f;
}}

nt maxFlow() { //first inititalize res, adjList, s and t
	int mf = 0;
	while (true) {
		f = 0;
		bitset<MAX_V> vis; vis[s] = true;
		queue<int> q; q.push(s);
		memset(p, -1, sizeof(p));
		while (!q.empty()) { //BFS
			int u = q.front(); q.pop();
			if (u == t) break;
			for (int j = 0; j < (int)adjList[u].size(); j++) {
				int v = adjList[u][j];
				if (res[u][v] > 0 && !vis[v]) {
					vis[v] = true; q.push(v); p[v] = u;
		}}}
		
		augment(t, INF); //add found path to max flow
		if (f == 0) break;
		mf += f;
	}
	return maxFlow;
}