Skip to content

Commit 42bed57

Browse files
committed
add Ford_Fulkerson Algorithm using dp
1 parent 4f07881 commit 42bed57

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import java.util.LinkedList;
2+
import java.util.Queue;
3+
import java.util.Scanner;
4+
import java.util.Vector;
5+
6+
public class Ford_Fulkerson {
7+
Scanner scan = new Scanner(System.in);
8+
final static int INF = 987654321;
9+
static int V; // edges
10+
static int[][] capacity, flow;
11+
12+
public static void main(String[] args) {
13+
System.out.println("V : 6");
14+
V = 6;
15+
capacity = new int[V][V];
16+
17+
capacity[0][1] = 12;
18+
capacity[0][3] = 13;
19+
capacity[1][2] = 10;
20+
capacity[2][3] = 13;
21+
capacity[2][4] = 3;
22+
capacity[2][5] = 15;
23+
capacity[3][2] = 7;
24+
capacity[3][4] = 15;
25+
capacity[4][5] = 17;
26+
27+
System.out.println("Max capacity in networkFlow : " + networkFlow(0, 5));
28+
}
29+
30+
private static int networkFlow(int source, int sink) {
31+
flow = new int[V][V];
32+
int totalFlow = 0;
33+
while (true) {
34+
Vector<Integer> parent = new Vector<>(V);
35+
for (int i = 0; i < V; i++)
36+
parent.add(-1);
37+
Queue<Integer> q = new LinkedList<>();
38+
parent.set(source, source);
39+
q.add(source);
40+
while (!q.isEmpty() && parent.get(sink) == -1) {
41+
int here = q.peek();
42+
q.poll();
43+
for (int there = 0; there < V; ++there)
44+
if (capacity[here][there] - flow[here][there] > 0 && parent.get(there) == -1) {
45+
q.add(there);
46+
parent.set(there, here);
47+
}
48+
}
49+
if (parent.get(sink) == -1)
50+
break;
51+
52+
int amount = INF;
53+
String printer = "path : ";
54+
StringBuilder sb = new StringBuilder();
55+
for (int p = sink; p != source; p = parent.get(p)) {
56+
amount = Math.min(capacity[parent.get(p)][p] - flow[parent.get(p)][p], amount);
57+
sb.append(p + "-");
58+
}
59+
sb.append(source);
60+
for (int p = sink; p != source; p = parent.get(p)) {
61+
flow[parent.get(p)][p] += amount;
62+
flow[p][parent.get(p)] -= amount;
63+
}
64+
totalFlow += amount;
65+
printer += sb.reverse() + " / max flow : " + totalFlow;
66+
System.out.println(printer);
67+
}
68+
69+
return totalFlow;
70+
}
71+
}

0 commit comments

Comments
 (0)