增广路求网路最大流

/* 算法竞赛入门经典  增广路求网路最大流
 * */
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class LargestFlow {
	static final int MAXN = 100;
	static int[][] cap = new int[MAXN][MAXN];// 边上最大容量
	static int[][] flow = new int[MAXN][MAXN];// 边上实际流量
	static int[] p = new int[MAXN];// 增广路上的父节点
	static int[] a = new int[MAXN];// 每个节点路径上的最小残量 a[t]就是整条路径上的最小残量
	static int n;// 顶点数
	static int m;// 边数
	static int s, t;// 起点和终点
	static LinkedList<Integer> q = new LinkedList<Integer>();
	static int f;// 从起点流出的最大流量值

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while ((n = scanner.nextInt()) > 0) {
			m = scanner.nextInt();
			s = scanner.nextInt();
			t = scanner.nextInt();
			for (int i = 1; i <= m; i++) {
				int u = scanner.nextInt();
				int v = scanner.nextInt();
				cap[u][v] = scanner.nextInt();
			}
			for (int i = 0; i <= n; i++) {
				Arrays.fill(flow[i], 0);
			}
			f = 0;
			for (;;) {
				Arrays.fill(a, 0);
				a[s] = Integer.MAX_VALUE;
				q.offer(s);
				while (q.size() > 0) {// 使用BFS找增光路径
					int u = q.poll();
					for (int v = 1; v <= n; v++) {
						if (a[v] == 0 && cap[u][v] > flow[u][v]) {// 找到新节点
							p[v] = u;// 记录父节点
							q.offer(v);// 入队列
							a[v] = Math.min(a[u], cap[u][v] - flow[u][v]);// 更新最小残量
						}
					}
				}
				if (a[t] == 0)
					break;// 不存在增广路 当前流已经是最大流
				for (int u = t; u != s; u = p[u]) {// 从汇点逆向更新流量值
					flow[p[u]][u] += a[t];// 更新正向流量
					flow[u][p[u]] -= a[t];// 更新逆向流量
				}
				f += a[t];
			}
			System.out.println(f);

			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					if (cap[i][j] > 0 && flow[i][j] > 0) {
						System.out.printf("%d %d %d/%d\n", i, j, flow[i][j],
								cap[i][j]);
					}
				}
			}
		}
	}
}
输入
6
10
1
6
1 2 16
1 3 13
2 3 10
3 2 4
2 4 12
4 3 9
3 5 14
5 4 7
4 6 20
5 6 4
输出
23
1 2 12/16
1 3 11/13
2 4 12/12
3 5 11/14
4 6 19/20
5 4 7/7
5 6 4/4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值