gpt4 book ai didi

c# - 在 C# 中使用 Krager 算法求解最小切割图

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:01:58 24 4
gpt4 key购买 nike

   public class Graph
{
public Graph()
{
Vertices = new Dictionary<int, List<int>>();
}

public Dictionary<int,List<int>> Vertices { get; set; }

public void ApplyKrager()
{
var random = new Random();
while (Vertices.Count > 2)
{

var randomIndex = random.Next(0,Vertices.Keys.Count);
var firstVertex = Vertices.Keys.ElementAt(randomIndex);
var secondVertex = Vertices[firstVertex].ElementAt(random.Next(0,Vertices[firstVertex].Count));
if (Vertices.ContainsKey(secondVertex))
{
Console.WriteLine();
Console.WriteLine("Merging " + firstVertex + " " + secondVertex);
//Merge
foreach (var edge in Vertices[secondVertex])
{
if (!Vertices[firstVertex].Contains(edge))
Vertices[firstVertex].Add(edge);
}

//change all the occurences of the secondVertex to the first
foreach (var vertex in Vertices)
{
if (vertex.Value.Contains(secondVertex))
{
vertex.Value.Remove(secondVertex);
vertex.Value.Add(firstVertex);
}
}
//Remove Self Loops
Vertices[firstVertex].RemoveAll(_ => _ == firstVertex);
Vertices.Remove(secondVertex);
}
//Print();
}

}

public void Print()
{
foreach (var v in Vertices)
{
Console.WriteLine("Vertex is : " + v.Key);
Console.Write("Edges are ");
foreach (var edge in v.Value)
{
Console.Write(edge + " ");
}
Console.WriteLine();
}
}
}

运行此代码的测试

    [Fact]
public void CheckForMinimumCuts()
{
var input = File.ReadAllLines(@"input.txt");
var directedEdges = new Dictionary<int, List<int>>();
foreach (var line in input)
{
var adjacency = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var vertex = Convert.ToInt32(adjacency[0]);
var edges = new List<int>();
for (int i = 1, j = 0; i < adjacency.Length; i++)
{
edges.Add(Convert.ToInt32(adjacency[i]));
}

directedEdges.Add(vertex, edges);
}

var cuts = new List<int>();
for (int i = 0; i < 500; i++)
{
var graph = new Graph {Vertices = directedEdges};
graph.ApplyKrager();
foreach (var v in graph.Vertices)
{
cuts.Add(v.Value.Count);
}
}

Console.WriteLine(cuts.Min());
}

//输入.txt

1 3 4 2
2 1 4 3
3 1 2 4
4 5 3 2 1
5 4 8 6 7
6 8 7 5
7 5 8 6
8 5 7 6

expected result: 1
cut is [(4,5)]

上面的算法没有给出正确的输出,即使运行多次实现随机化也是如此。

我选择的随机边是否有偏差?

我应该改为执行 cuts.Add(graph.Vertices.first().count() 吗?

或者我的算法编码不正确,因此没有正确输出的机会?

注意:试图将此问题标记为家庭作业..找不到标签。

最佳答案

随机收缩最小切割算法要求您统一随机选择一条。您统一随机选择一个顶点,然后统一随机选择与该顶点关联的边。

您可能还有一个我看不到的实现错误,因为我不懂 C#。如果您的算法在 8 顶点图上进行 500 次迭代仍无法识别最小切割,我会感到惊讶。 new Random() 是否每次都生成具有相同种子的 RNG?

关于c# - 在 C# 中使用 Krager 算法求解最小切割图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17777054/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com