Ford Fulkerson 有向图权重

如何解决Ford Fulkerson 有向图权重

我正在处理一项作业,因为我们正在进入我们的图论单元,该单元是福特富尔克森算法的实现。这个想法是我们有一个带有一定数量节点的加权有向图。我们还提供了图本身,它是有向边和节点的集合,但是,鉴于节点和边的构造,我们必须使用边作为我们的遍历方法(它们是由起始节点、权重组成的对象),和结束节点).

我已经解决了 DFS,但在实际生成最终加权图时遇到了困难。就目前而言,我能够获得正确的最大流量,但我的边缘附加了错误的权重,目前甚至没有加到最大流量。我怀疑错误在于我如何计算残差图边缘的流量,因为它目前仅从当前权重值中减去流量。我知道在常规的 Ford Fulkerson 中,每条边的残差都会有两个方向,但是在我实现它的方式中,我只有一个,因为 Graphs 的构造函数没有这样做。我还需要在最后返回我的残差以查看所有顶点的值及其权重,所以我应该创建一个双向的第三个图,并将残差边的值指定为两个方向的总和在双向图中?

福特富尔克森班

import java.lang.reflect.Array;
import java.util.*;
import java.io.File;

public class FordFulkerson {

    public static ArrayList<Integer> pathDFS(Integer source,Integer destination,WGraph graph) {
        Stack<Integer> toVisit = new Stack<>();
        ArrayList<Integer> visited = new ArrayList<>();
        HashMap<Integer,Integer> parents = new HashMap<>();
        toVisit.push(0);
        boolean flag = false;
        while (!toVisit.isEmpty()) {
            int node = toVisit.pop();
            visited.add(node);
            if (node == destination) {
                flag = true;
                break;
            }
            for (Edge curEdge : graph.getEdges()) {
                if ((curEdge.nodes[0] == node) &&(curEdge.weight>0)&&(!visited.contains(curEdge.nodes[1]))) {
                    toVisit.push(curEdge.nodes[1]);
                    parents.put(curEdge.nodes[1],curEdge.nodes[0]);
                }
            }
        }
        if (flag) {
            ArrayList<Integer> path = new ArrayList<>();
            int current = destination;
            while (current != source) {
                path.add(0,current);
                current = parents.get(current);
            }
            path.add(0,source);
            return path;
        }
        return new ArrayList<>();
    }


    public static String fordfulkerson(WGraph graph) {
        ArrayList<Integer> result = pathDFS(graph.getSource(),graph.getDestination(),graph);
        WGraph residual = new WGraph(graph);
        String answer = "";
        int maxFlow = 0;
        while (!result.isEmpty()) {
            int flow = Integer.MAX_VALUE;
            int parentNode;
            int childNode;
            for (int i=result.size()-1; 0 < i; i--) {
                parentNode = result.get(i-1);
                childNode = result.get(i);
                flow = Math.min(flow,residual.getEdge(parentNode,childNode).weight);
            }
            for (int i=0; i < result.size()-1; i++) {
                parentNode = result.get(i);
                childNode = result.get(i+1);
                residual.getEdge(parentNode,childNode).weight -= flow;
//              residual.getEdge(parentNode,childNode).weight -= flow;
            }
            maxFlow += flow;
            result = pathDFS(graph.getSource(),residual);
        }
        answer += maxFlow + "\n" + residual.toString();
        return answer;

}
    

     public static void main(String[] args){
        String file = args[0];
        File f = new File(file);
        WGraph g = new WGraph(file);
        System.out.println(fordfulkerson(g));
     }
}

图和边类

import java.io.*;
import java.util.*;

class Edge{
    
    public int[] nodes = new int[2]; /*The nodes connected by the edge*/
    public Integer weight; /*Integer so we can use Comparator*/
    
    Edge(int i,int j,int w){
        this.nodes[0] = i;
        this.nodes[1] = j;
        this.weight = w;
    }

    @Override
    public String toString() {
        return String.format("Edge(%s,%s,%s)",this.nodes[0],this.nodes[1],this.weight);
    }

}

public class WGraph{

    private ArrayList<Edge> edges = new ArrayList<Edge>();
    private ArrayList<Integer> nodes = new ArrayList<Integer>();
    private int nb_nodes = 0;
    private Integer source = 0;
    private Integer destination =0;

    WGraph() {
    }
    
    WGraph(WGraph graph) {
        for(Edge e:graph.edges){
            this.addEdge(new Edge(e.nodes[0],e.nodes[1],e.weight));
        }
        this.source = graph.source;
        this.destination = graph.destination;
    }

    WGraph(String file) throws RuntimeException {
        try {
            Scanner f = new Scanner(new File(file));
            String[] ln = f.nextLine().split("\\s+"); /*first line is the source and destination*/
            this.source = Integer.parseInt(ln[0]);
            this.destination = Integer.parseInt(ln[1]);
            int number_nodes = Integer.parseInt(f.nextLine()); /*second line is the number of nodes*/

            while (f.hasNext()){
                String[] line = f.nextLine().split("\\s+");
                /*Make sure there is 3 elements on the line*/
                if (line.length != 3){
                    continue;
                }
                int i = Integer.parseInt(line[0]);
                int j = Integer.parseInt(line[1]);
                int w = Integer.parseInt(line[2]);
                Edge e = new Edge(i,j,w);
                this.addEdge(e);
            }
            f.close();

            /*Sanity checks*/
            if (number_nodes != this.nb_nodes){
                throw new RuntimeException("There are " + this.nb_nodes + " nodes while the file specifies " + number_nodes);
            }
            for (int i = 0; i < this.nodes.size(); i++){
                if ((this.nodes.get(i) >= this.nb_nodes) || (this.nodes.get(i) < 0)){
                    throw new RuntimeException("The node " + this.nodes.get(i) + " is outside the range of admissible values,between 0 and " + this.nb_nodes + "-1");
                }
            }
            if(!this.nodes.contains(source)){
                throw new RuntimeException("The source must be one of the nodes");
            }
            if(!this.nodes.contains(destination)){
                throw new RuntimeException("The destination must be one of the nodes");
            }

        }
        catch (FileNotFoundException e){
            System.out.println("File not found!");
            System.exit(1);
        }


    }
    
    public void addEdge(Edge e) throws RuntimeException{
        /*Ensures that it is a new edge if both nodes already in the graph*/
        int n1 = e.nodes[0];
        int n2 = e.nodes[1];
        if (this.nodes.indexOf(n1) >= 0 && this.nodes.indexOf(n2) >= 0){
            for (int z = 0; z < this.edges.size(); z++){
                int[] n = this.edges.get(z).nodes;
                if ((n1 == n[0] && n2 == n[1])){
                    throw new RuntimeException("The edge (" + n1 + "," + n2 + ") already exists");
                }
            }
        }

        /*Update nb_nodes if necessary*/
        if (this.nodes.indexOf(n1) == -1){
            this.nodes.add(n1);
            this.nb_nodes += 1;
        }
        if (this.nodes.indexOf(n2) == -1){
            this.nodes.add(n2);
            this.nb_nodes += 1;
        }

        this.edges.add(e);
    }
    
    public Edge getEdge(Integer node1,Integer node2){      
        for(Edge e:edges){
            if(e.nodes[0]==node1 && e.nodes[1]==node2){
                return e;
            }
        }
        return null;
    }
    public void setSource(int source){
        this.source = source;
    }
    
    public void setDestination(int destination){
        this.destination = destination;
    }
    
    public int getSource(){
        return this.source;
    }
    
    public int getDestination(){
        return this.destination;
    }
    
    public void setEdge(Integer node1,Integer node2,int weight){
        for(Edge e:edges){
            if(e.nodes[0]==node1 && e.nodes[1]==node2){
                e.weight=weight;
            }
        }
    }

    public ArrayList<Edge> listOfEdgesSorted(){
        ArrayList<Edge> edges = new ArrayList<Edge>(this.edges);
        Collections.sort(edges,new Comparator<Edge>() {
            public int compare(Edge  e1,Edge  e2) 
            {   
                return  e2.weight.compareTo(e1.weight);
            }   
        }); 
        return edges;
    }

    public ArrayList<Edge> getEdges(){
        return this.edges;
    }

    public int getNbNodes(){
        return this.nb_nodes;
    }

    public String toString(){
        String out = Integer.toString(this.source)+ " " + Integer.toString(this.destination)+"\n";
        out += Integer.toString(this.nb_nodes);
        for (int i = 0; i < this.edges.size(); i++){
            Edge e = edges.get(i);
            out += "\n" + e.nodes[0] + " " + e.nodes[1] + " " + e.weight;
        }
        return out;
    }
}

作为参考,我有输入

0 5
6
0 1 16
0 2 13
1 3 12
2 1 4
2 4 14
3 2 9
3 5 20
4 3 7
4 5 4

它定义了一个具有 5 个节点和 9 个边的起始​​图,它们的权重偏向一边。正确的输出是:

23
0 5
6
0 1 12
0 2 11
1 3 12
2 1 0
2 4 11
3 2 0
3 5 19
4 3 7
4 5 4

但是,在运行我的 Ford Fulkerson 时,我得到以下输出:

23
0 5
6
0 1 6
0 2 0
1 3 0
2 1 2
2 4 3
3 2 9
3 5 1
4 3 0
4 5 0

我一直在查看以下 GeeksforGeeks article,其中它们以有向图开始,但稍后能够以某种方式反向访问顶点:

        // update residual capacities of the edges and
        // reverse edges along the path
        for (v = t; v != s; v = parent[v]) {
            u = parent[v];
            rGraph[u][v] -= path_flow;
            rGraph[v][u] += path_flow;
        }

任何关于从哪里开始寻找或我做错了什么的指示或提示都会很棒。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res