[ford-fulkerson] 利用残量图求解最大流

本文介绍了一种基于残量图实现的最大流算法——Ford-Fulkerson算法,并提供了一个具体的Java实现示例。该算法通过不断寻找源节点到汇节点的增广路径来逐步增加流值,直至无法找到新的增广路径为止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Wikipedia 上关于Ford-Fulkerson算法的描述如下

Algorithm Ford-Fulkerson

Inputs Graph /,G with flow capacity /,c , a source node /,s , and a sink node /,t
Output A flow /,f from /,s to /,t which is a maximum
  1. f(u,v) /leftarrow 0 for all edges /,(u,v)
  2. While there is a path /,p from /,s to /,t in /,G_f , such that /,c_f(u,v) > 0 for all edges (u,v) /in p :
    1. Find /,c_f(p) = /min/{c_f(u,v) /;|/; (u,v) /in p/}
    2. For each edge (u,v) /in p
      1. f(u,v) /leftarrow f(u,v) + c_f(p) (Send flow along the path )
      2. f(v,u) /leftarrow f(v,u) - c_f(p) (The flow might be "returned" later )

虽然算法貌似很简单,但是算法正确性的证明过程确实比较困难,由于本人才疏学浅,所以证明过程虽然看了好多便,现在仍然不甚明了,今天太晚了,明天继续搞,先把今晚用残量图实现的Ford-Fulkerson算法贴出来,注释比较详细。

package com.FeeLang; public class FordFulkerson { public static void main(String[] args){ // int[][] net = new int[4][4]; // net[0][1] = 1000; // net[0][2] = 1000; // net[1][2] = 1; // net[1][3] = 1000; // net[2][3] = 1000; int nodes = 6; int[][] capacity = new int[nodes][nodes]; capacity[0][1] = 7; capacity[0][2] = 6; capacity[1][3] = 4; capacity[1][4] = 2; capacity[2][3] = 2; capacity[2][4] = 3; capacity[3][5] = 9; capacity[4][5] = 5; FordFulkerson maxFlow = new FordFulkerson(capacity, nodes); int max = maxFlow.getMaxFlow(0, 5); System.out.println(max); } 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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值