我有一些简单的Java / JUNG代码,它们创建有向图,添加具有权重和容量值的边,并运行从源节点到宿节点的最大流量分析。
如果您具有:A ---(容量2)-----> B ----(容量5)----> C,并且想要从A-> C中找到最大流量,则该值为2。
import edu.uci.ics.jung.algorithms.flows.EdmondsKarpMaxFlow;
import edu.uci.ics.jung.graph.DirectedSparseMultigraph;
import edu.uci.ics.jung.graph.util.EdgeType;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import java.util.HashMap;
import java.util.Map;
public class stack {
static int edgeCount = 0;
static class MyNode {
int id;
public MyNode(int id) {
this.id = id;
}
public String toString() {
return "V"+id;
}
}
static class MyLink {
double capacity;
double weight;
int id;
public MyLink(double weight, double capacity) {
this.id = edgeCount++;
this.weight = weight;
this.capacity = capacity;
}
public String toString() {
return "E"+id;
}
}
public static void main(String[] args){
DirectedSparseMultigraph<MyNode, MyLink> g = new DirectedSparseMultigraph<MyNode, MyLink>();
Transformer<MyLink, Double> capTransformer = new Transformer<MyLink, Double>(){
public Double transform(MyLink link) {
return link.capacity;
}
};
Map<MyLink, Double> edgeFlowMap = new HashMap<MyLink, Double>();
// This Factory produces new edges for use by the algorithm
Factory<MyLink> edgeFactory = new Factory<MyLink>() {
public MyLink create() {
return new MyLink(1.0, 1.0);
}
};
// Create some MyNode objects to use as vertices
MyNode n1 = new MyNode(1);
MyNode n2 = new MyNode(2);
MyNode n3 = new MyNode(3);
MyNode n4 = new MyNode(4);
MyNode n5 = new MyNode(5);
MyNode n6 = new MyNode(6);
MyNode n7 = new MyNode(7);
// Add some directed edges along with the vertices to the graph
g.addEdge(new MyLink(2.0, 48),n1, n2, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 58),n2, n3, EdgeType.DIRECTED);
g.addEdge(new MyLink(3.0, 192), n3, n5, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 48), n5, n4, EdgeType.DIRECTED);
g.addEdge(new MyLink(2.0, 20), n6, n1, EdgeType.DIRECTED);
g.addEdge(new MyLink(8, 24), n7, n4, EdgeType.DIRECTED);
System.out.println("RUNNING EDMONDS KARP MAX FLOW FOR SOURCE " + n1.toString() + " TO SINK " + n2.toString());
EdmondsKarpMaxFlow<MyNode, MyLink> edk = new EdmondsKarpMaxFlow(g, n1, n2, capTransformer, edgeFlowMap, edgeFactory);
edk.evaluate();
System.out.println("The max flow is: " + edk.getMaxFlow());
}
}
运行此命令将输出:
从源V1到SINK V2运行EDMONDS KARP最大流量最大流量
是:48
如何编写算法使其在每个可能的源和汇对上运行,以便可以在图中看到所有路径的最大流量?完全陌生的东西,所以任何帮助!
最佳答案
只需为每对节点运行算法。没有已知的算法对有向图更有效:All pair Maximum Flow