微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift]DJSet

 1 public class DJSet
 2 {
 3     var upper:[Int]
 4     var w:[Int]
 5     
 6     init(_ n:Int)
 7     {
 8         upper = [Int](repeating:-1,count:n)
 9         w = [Int](repeating:0,count:n)
10     }
11     
12     func root(_ x:Int) -> Int
13     {
14         if(upper[x] < 0)
15         {
16             return x
17         }
18         else
19         {
20             upper[x] = root(upper[x])
21             return upper[x]
22         }
23     }
24     
25     func equiv(_ x:Int,_ y:Int) -> Bool
26     {
27         return root(x) == root(y)
28     }
29     
30     func union(_ x:Int,_ y:Int) -> Bool
31     {
32         var x:Int = root(x)
33         var y:Int = root(y)
34         if x != y
35         {
36             if upper[y] < upper[x]
37             {
38                 var d:Int = x
39                 x = y
40                 y = d
41             }
42             upper[x] += upper[y]
43             upper[y] = x
44             w[x] += w[y]
45         }
46         return x == y
47     }
48     
49     func count() -> Int
50     {
51         var ct:Int = 0
52         for u in upper
53         {
54             if u < 0
55             {
56                 ct += 1
57             }
58         }
59         return ct
60     }
61 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐