最大流(二)---朴素算法

https://www.cnblogs.com/fzl194/p/8855101.html

package graphModel;

import java.util.Arrays;
import java.util.LinkedList;

public class FordFulkson {
    public static int inf = 1000;// 表示两点之间不连接
    public static int maxn = 1000;// 节点预分配的最大个数,防止越界

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int N = 6;//实际节点个数
        int S = 0;
        int T = N-1;
        
        int[][] dag = { { 0, 8, inf, 7, inf, inf }, { inf, 0, 9, 5, inf, inf }, { inf, inf, 0, 2, inf, 5 },
                { inf, inf, inf, 0, 9, inf }, { inf, inf, 6, inf, 0, 10 }, { inf, inf, inf, inf, inf, 0 } };
        Graph graph = new Graph();
        graph.initSolveMaxFlow(dag);
        Graph.Edge[] edges = graph.getEdges();
        int[] head = graph.getHead();
        
        int flow = 0;
        int[] flowNodes = new int[maxn];//每个点目前分配的流量
        int[] preNode = new int[maxn];//p[i]从原点s到终点t的节点i的前一条边的编号
        Arrays.fill(preNode, -1);
        while(true) {
            //每轮迭代,每个节点在本轮分配的流量初始化为0
            Arrays.fill(flowNodes, 0);
           // Arrays.fill(preNode, -1);
            LinkedList<Integer> queue = new LinkedList<>();
            queue.add(S);
            flowNodes[S]=inf;
            while(!queue.isEmpty()) {
                int curNode = queue.poll();
                for(int i=head[curNode];i!=-1;i=edges[i].next) {
                    int to = edges[i].to;
                    if( flowNodes[to]==0 && edges[i].w>0) {
                        int tmp = Math.min(flowNodes[curNode], edges[i].w);
                        flowNodes[to] +=tmp;
                        preNode[to]=curNode;
                        queue.add(to);
                    }
                    
                }
                if(flowNodes[T]!=0)
                    break;//如果已经流到了终点t,退出本次找增广路
            }
            if(flowNodes[T]==0)
                break;//如果所有路都已经试过,水不能流到终点,说明已经没有增广路,已经是最大流   
            //分配流量
         
            for(int i=T; i!=S;i=preNode[i]) {
                int u = preNode[i];
                int v=i;
                for(int j=head[u];j!=-1;j=edges[j].next) {
                    if(edges[j].to == v) {
                        edges[j].w-=flowNodes[T];
                        edges[j+1].w+=flowNodes[T];
                    }
                    
                }
            }
            flow = flow+flowNodes[T];
        }
        System.out.println(flow);

    }

}

 

点赞