[英]Coalesce intersecting sets into disjoint sets
我正在尋找一種算法來將可能相交的集合列表合並為沒有相交的集合列表。
例如:
my_sets = set(1, 2, 3), set(5, 6), set(4, 5, 6), set(4, 7), set(3, 8), set(9)
應該產生:
my_coalesced_sets = set(1, 2, 3, 8), set(4, 5, 6, 7), set(9)
理想情況下,算法 O(n)...
應 Ruben 的要求,這是我嘗試過的許多算法之一,但沒有產生正確的結果:
fun main(){
val l = mutableListOf(setOf(1, 2, 3), setOf(5, 6), setOf(4, 5, 6), setOf(4, 7), setOf(3, 8), setOf(9))
while (true){
val removes = mutableListOf<Set<Int>>()
var current = l.removeFirst()
l.filter { current.intersect(it).isNotEmpty() }.forEach {
current = current union it
removes += it
}
l += current
if (removes.isEmpty()){
break
}
l.removeAll(removes)
}
print(l)
}
這就是不相交集數據結構的目的。 只需為每個輸入集中的每個連續對添加一條邊(“並集”),結果將是合並集。 運行時間基本上是線性的(非常輕微的超線性,但這只是理論上的差異)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.