【问题标题】:How to get max_weight_matching in java如何在 java 中获取 max_weight_matching
【发布时间】:2020-09-09 10:44:09
【问题描述】:

我有一个加权和非二分图,并希望获得最大权重匹配。我已经使用 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 库但找不到解决方案”是什么意思?

标签: java graph graph-theory jgrapht weighted-graph


【解决方案1】:

这是使用 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]

【讨论】:

    猜你喜欢
    • 2017-04-24
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2014-02-19
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多