Wikipedia 上关于Ford-Fulkerson算法的描述如下
Algorithm
Ford-Fulkerson
- Inputs
Graph
with flow capacity
, a source node
, and a sink node - Output
A flow
from
to
which is a maximum
for all edges- While there is a path
from
to
in
, such that
for all edges
:- Find
- For each edge
(Send flow along the path
)
(The flow might be "returned" later
)
虽然算法貌似很简单,但是算法正确性的证明过程确实比较困难,由于本人才疏学浅,所以证明过程虽然看了好多便,现在仍然不甚明了,今天太晚了,明天继续搞,先把今晚用残量图实现的Ford-Fulkerson算法贴出来,注释比较详细。
public FordFulkerson(int[][] net, int nodes){
this.net = net;
this.nodes = nodes;
pre = new int[nodes];
visited = new boolean[nodes];
}
public int getMaxFlow(int s, int t){
//initial the residual capacities
residual = net;
int maxFlow = 0;
while (true){
for (int i = 0; i < nodes; i++)
visited[i] = false;
//initial residual capacities
getPath(s, t);
if (!visited[t]){ // not find a path from s to t
break;
}
//get the min capacity of the path
int min = Integer.MAX_VALUE;
for (int i = t; i > s; i = pre[i]){
min = Math.min(min, residual[pre[i]][i]);
}
//send min units of flow to the path.
//Update residual capacities
for (int i = t; i > s; i = pre[i]){
residual[pre[i]][i] -= min;
residual[i][pre[i]] += min;
}
maxFlow += min;
}
return maxFlow;
}
//search a path from s to t
public void getPath(int s, int t){
visited[s] = true;
for (int i = 0; i < nodes; i++){
if (!visited[i] && residual[s][i] > 0){
visited[i] = true;
pre[i] = s;
getPath(i, t);
}
}
}
private boolean[] visited;
private int[][] net;
private int[][] residual;
private int[] pre;
private int nodes;