package com.bluecup.org;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class MaxFlow {
/**
* @param args
*/
static int n;
static int d[][] = new int[10 + 1][10 + 1];
static int cost[][] = new int[10 + 1][10 + 1];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int value, money;
n = scan.nextInt();
for (int i = 1; i <= n; i++)
Arrays.fill(d[i], -1);
for (int i = 1; i <= n; i++)
Arrays.fill(cost[i], -1);
for (int i = 1; i < n + 1; i++)
Arrays.fill(flow[i], -1);
do {
int i = scan.nextInt();
int j = scan.nextInt();
value = scan.nextInt();
money = scan.nextInt();
if (value > 0) {
d[i][j] = value;
cost[i][j] = money;
cost[j][i] = -money;
flow[i][j] = 0;
if (flow[j][i] != 0)
flow[j][i] = value;
}
} while (value > 0);
System.out.println(getMaxflow());
}
static int maxmoney;
static int maxflow;
static int flow[][] = new int[10 + 1][10 + 1];
static int fa[] = new int[10 + 1];
private static int getMaxflow() {
// TODO Auto-generated method stub
LinkedList<Integer> list = new LinkedList<Integer>();
int t[] = new int[n + 1];
while (true) {
// 初始值处理
boolean used[] = new boolean[n + 1];
t[1] = 0;
for (int i = 2; i <= n; i++) {
t[i] = Integer.MAX_VALUE;
}
Arrays.fill(used, false);
list.add(1);
// 个人理解下步为广度搜索最值处理
while (list.size() != 0) {
int v = list.pop();
System.out.println(v);
used[v] = false;
for (int i = 1; i <= n; i++) {
if (flow[v][i] < d[v][i]) {
if (t[i] > (t[v] + cost[v][i])) {
fa[i] = v;
t[i] = t[v] + cost[v][i];
if (used[i] == false) {
list.add(i);
used[i] = true;
}
}
}
}
}
if (t[n] == Integer.MAX_VALUE)
break;
int a = Integer.MAX_VALUE;
for (int i = n; i != 1; i = fa[i]) {
if (a > d[fa[i]][i] - flow[fa[i]][i])
a = d[fa[i]][i] - flow[fa[i]][i];
}
for (int i = n; i != 1; i = fa[i]) {
flow[fa[i]][i] = flow[fa[i]][i] + a;
flow[i][fa[i]] = flow[i][fa[i]] - a;
}
maxflow = maxflow + a;
maxmoney = maxmoney + a * t[n];
}
return maxmoney;
}
}
最小费用最大流问题
最新推荐文章于 2021-03-04 21:28:30 发布