如何在 java 中获得 max_weight_matching
How to get max_weight_matching in java
我有一个加权非二分图,想获得最大权重匹配。我已经使用 python networkx 库完成了任务,并正在寻找 java 的替代库。我查看了 JGraphT 库,但找不到解决方案。
import networkx as nx
import networkx.algorithms.matching as matching
G=nx.Graph()
G.add_edge(1,2,weight = 30)
G.add_edge(1,3,weight = 100)
G.add_edge(1,4,weight = 30)
G.add_edge(2,3,weight = 0)
G.add_edge(2,4,weight = 30)
G.add_edge(3,4,weight = 30)
M = matching.max_weight_matching(G,maxcardinality=True)
print(list(M))
//OUTPUT: [(1, 3), (2, 4)]
这是使用 JGraphT 的解决方案:
Graph<Integer, DefaultWeightedEdge> g = new SimpleWeightedGraph<>(SupplierUtil.createIntegerSupplier(1), SupplierUtil.createDefaultWeightedEdgeSupplier());
Integer v1=g.addVertex();
Integer v2=g.addVertex();
Integer v3=g.addVertex();
Integer v4=g.addVertex();
Graphs.addEdge(g, v1, v2, 30);
Graphs.addEdge(g, v1, v3, 100);
Graphs.addEdge(g, v1, v4, 30);
Graphs.addEdge(g, v2, v3, 0);
Graphs.addEdge(g, v2, v4, 30);
Graphs.addEdge(g, v3, v4, 30);
MatchingAlgorithm<Integer, DefaultWeightedEdge> alg = new KolmogorovWeightedMatching<>(g, ObjectiveSense.MAXIMIZE);
System.out.println(alg.getMatching());
输出:
Matching [edges=[(1 : 3), (2 : 4)], weight=130.0]
我有一个加权非二分图,想获得最大权重匹配。我已经使用 python networkx 库完成了任务,并正在寻找 java 的替代库。我查看了 JGraphT 库,但找不到解决方案。
import networkx as nx
import networkx.algorithms.matching as matching
G=nx.Graph()
G.add_edge(1,2,weight = 30)
G.add_edge(1,3,weight = 100)
G.add_edge(1,4,weight = 30)
G.add_edge(2,3,weight = 0)
G.add_edge(2,4,weight = 30)
G.add_edge(3,4,weight = 30)
M = matching.max_weight_matching(G,maxcardinality=True)
print(list(M))
//OUTPUT: [(1, 3), (2, 4)]
这是使用 JGraphT 的解决方案:
Graph<Integer, DefaultWeightedEdge> g = new SimpleWeightedGraph<>(SupplierUtil.createIntegerSupplier(1), SupplierUtil.createDefaultWeightedEdgeSupplier());
Integer v1=g.addVertex();
Integer v2=g.addVertex();
Integer v3=g.addVertex();
Integer v4=g.addVertex();
Graphs.addEdge(g, v1, v2, 30);
Graphs.addEdge(g, v1, v3, 100);
Graphs.addEdge(g, v1, v4, 30);
Graphs.addEdge(g, v2, v3, 0);
Graphs.addEdge(g, v2, v4, 30);
Graphs.addEdge(g, v3, v4, 30);
MatchingAlgorithm<Integer, DefaultWeightedEdge> alg = new KolmogorovWeightedMatching<>(g, ObjectiveSense.MAXIMIZE);
System.out.println(alg.getMatching());
输出:
Matching [edges=[(1 : 3), (2 : 4)], weight=130.0]