[英]Karger's Algorithm
I'm trying to implement the min-cut Karger's algorithm in Java.我正在尝试用 Java 实现 min-cut Karger 算法。 For this, I created a Graph class which stores a SortedMap, with an integer index as key and a Vertex object as value, and an ArrayList of Edge objects.
为此,我创建了一个 Graph 类,它存储一个 SortedMap,一个整数索引作为键,一个 Vertex 对象作为值,以及一个 Edge 对象的 ArrayList。 Edges stores the index of its incident vertices.
Edges 存储其事件顶点的索引。 Than I merge the vertices of some random edge until the number of vertices reach 2. I repeat this steps a safe number of times.
然后我合并一些随机边的顶点,直到顶点数达到 2。我重复这个步骤安全的次数。 Curiously, in my output I get 2x the number of crossing edges.
奇怪的是,在我的输出中,我得到了 2 倍的交叉边数。 I mean, if the right answer is 10, after execute n times the algorithm (for n sufficient large), the min of these execution results is 20, what makes me believe the implementation is almost correct.
我的意思是,如果正确答案是 10,在执行 n 次算法后(对于 n 足够大),这些执行结果的最小值是 20,这让我相信实现几乎是正确的。 This is the relevant part of code:
这是代码的相关部分:
void mergeVertex(int iV, int iW) {
for (int i = 0; i < edges.size(); i++) {
Edge e = edges.get(i);
if (e.contains(iW)) {
if (e.contains(iV)) {
edges.remove(i);
i--;
} else {
e.replace(iW, iV);
}
}
}
vertices.remove(iW);
}
public int kargerContraction(){
Graph copy = new Graph(this);
Random r = new Random();
while(copy.getVertices().size() > 2){
int i = r.nextInt(copy.getEdges().size());
Edge e = copy.getEdges().get(i);
copy.mergeVertex(e.getVertices()[0], e.getVertices()[1]);
}
return copy.getEdges().size()/2;
}
Actually the problem was much more simple than I thought.其实问题比我想象的要简单得多。 While reading the .txt which contains the graph data, I was counting twice each edge, so logically the minCut returned was 2 times the right minCut.
在读取包含图形数据的 .txt 时,我对每条边进行了两次计数,因此从逻辑上讲,返回的 minCut 是正确 minCut 的 2 倍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.