gpt4 book ai didi

c# - C# 中的不相交集实现

转载 作者:行者123 更新时间:2023-11-30 12:55:45 24 4
gpt4 key购买 nike

我没有在 C# 中使用按等级实现联合 找到不相交集 的任何良好实现,所以我实现了自己的。它以 O(log n) 时间复杂度工作。

是否有更快的(或 C# 中的内置实现)或者我可以使用自己的实现?

class DisjointSetUBR
{
int[] parent;
int[] rank; // height of tree

public DisjointSetUBR(int[] arr)
{
parent = new int[arr.Length +1];
rank = new int[arr.Length + 1];
}

public void MakeSet(int i)
{
parent[i] = i;
}

public int Find(int i)
{
while (i!=parent[i]) // If i is not root of tree we set i to his parent until we reach root (parent of all parents)
{
i = parent[i];
}
return i;
}

// Path compression, O(log*n). For practical values of n, log* n <= 5
public int FindPath(int i)
{
if (i!=parent[i])
{
parent[i] = FindPath(parent[i]);
}
return parent[i];
}

public void Union(int i, int j)
{
int i_id = Find(i); // Find the root of first tree (set) and store it in i_id
int j_id = Find(j); // // Find the root of second tree (set) and store it in j_id

if (i_id == j_id) // If roots are equal (they have same parents) than they are in same tree (set)
{
return;
}

if (rank[i_id] > rank[j_id]) // If height of first tree is larger than second tree
{
parent[j_id] = i_id; // We hang second tree under first, parent of second tree is same as first tree
}
else
{
parent[i_id] = j_id; // We hang first tree under second, parent of first tree is same as second tree
if (rank[i_id] == rank[j_id]) // If heights are same
{
rank[j_id]++; // We hang first tree under second, that means height of tree is incremented by one
}
}
}
}

最佳答案

  1. 在 Sedgewick 教授的“算法”一书中,他 mentions “加权快速联合与路径压缩”,它应该具有反阿克曼函数摊销查找/联合的时间。

  2. 你是对的,.Net 中没有任何 Disjoint Set 的实现。

关于c# - C# 中的不相交集实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383172/

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