-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFlow.java
More file actions
47 lines (46 loc) · 1.21 KB
/
Flow.java
File metadata and controls
47 lines (46 loc) · 1.21 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
// brett fazio, flow (Ford)
import java.util.*;
public class Flow {
static int source, sink, nodes, edges;
static boolean[] seen;
static int[][] cap;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
nodes = sc.nextInt();
edges = sc.nextInt();
// take in the amount of possible flow between nodes
seen = new boolean[nodes];
cap = new int[nodes][nodes];
for (int i = 0; i < edges; i++) {
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
int weight = sc.nextInt();
cap[a][b] = weight;
}
source = sc.nextInt()-1;
sink = sc.nextInt()-1;
int answer = 0;
int flowsent = 1;
while (flowsent > 0) {
Arrays.fill(seen, false);
flowsent = dfs(source, Integer.MAX_VALUE);
answer += flowsent;
}
System.out.println(answer);
}
static int dfs(int i, int flow) {
if (i == sink) return flow;
seen[i] = true; // flow = min(flow,nodecap[i]);
for (int j = 0; j < nodes; j++) { // loop through all possible locations I can hit
if (!seen[j] && cap[i][j] > 0) {
int hit = dfs(j,Math.min(flow,cap[i][j]));
if (hit > 0) {
cap[i][j] -= hit;
cap[j][i] += hit;
return hit;
}
}
}
return 0;
}
}