import java.util.*;
/**
*
* @author Administrator dai liyun
* @since 2010.3.11 求网络最大流
*/
public class MaxFlow {
private int[][] edges;/*
* = { { 0, 1, 1, 0, 0 }, { 0, 0, 0, 1, 1 }, { 0, 0, 0,
* 1, 0 }, { 0, 0, 0, 0, 1 }, { 0, 0, 0, 0, 0 } };
*/
private int[][] flows;/* = edges; */
private boolean[] label;
final int length;
public MaxFlow() {
System.out.println("enter the graphics size ");
Scanner cin = new Scanner(System.in);
length = cin.nextInt();
edges = new int[length][length];
flows = new int[length][length];
label = new boolean[length];
System.out.println("enter Adjacency matrix");
for (int i = 0; i < length; i++) {
label[i] = false;
for (int j = 0; j < length; j++) {
edges[i][j] = cin.nextInt();
flows[i][j] = edges[i][j];
}
}
search();
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
if (flows[i][j] > 0) {
flows[i][j] -= edges[i][j];
}
}
}
System.out.println("search end the result is:");
for (int i = 0; i < length; i++) {
System.out.println();
for (int j = 0; j < length; j++) {
System.out.print(" " + flows[i][j]);
}
}
}
public void search() {
int minLabelIndex = 0;
int minMax = 0;
boolean state = true;
while (minLabelIndex < length - 1) {
int[] path = new int[length];
int pathIndex = 0, searchV = minLabelIndex;
for (int i = 0; i < length; i++) {
path[i] = -1;
}
minMax = Integer.MAX_VALUE;
searchV = minLabelIndex;
path[pathIndex++] = minLabelIndex;
while (searchV < length - 1) {
int t = 0;
int next = 0;
for (int h = 0; h < length; h++) {
if (canChoose(searchV, h, t, path)) {
t = edges[searchV][h];
next = h;
}
}
minMax = (minMax < t) ? minMax : t;
if (minMax == 0) {
label[searchV] = true;
for (int i = 0; i < length; i++) {
if (!label[i]) {
minLabelIndex = i;
break;
}
}
state = false;
break;
}
searchV = next;
path[pathIndex++] = searchV;
}
if (state) {
int i = 0;
while (i < length - 1 && path[i + 1] > -1) {
int xlabel = path[i];
int ylabel = path[i + 1];
edges[xlabel][ylabel] -= minMax;
edges[ylabel][xlabel] += minMax;
i++;
}
} else
state = true;
}
}
private boolean canChoose(int n, int h, int t, int[] temp) {
if (!label[h] && edges[n][h] >= t && h != n && noLoop(temp, h))
return true;
return false;
}
private boolean noLoop(int[] temp, int x) {
int i = 0;
while (temp[i] != -1) {
if (temp[i] == x)
return false;
i++;
}
return true;
}
public static void main(String[] args) {
MaxFlow f = new MaxFlow();
}
}
没日一算法 (网络最大流)3.12
最新推荐文章于 2024-10-16 21:06:05 发布