-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.rb
59 lines (45 loc) · 761 Bytes
/
test.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class UnionFindTree
class ParArray < Hash
def [] key
self[key] = key if super(key).nil?
super(key)
end
end
class SizeArray < Hash
def [] key
self[key] = 1 if super(key).nil?
super(key)
end
end
def initialize()
@par = ParArray.new
@size = SizeArray.new
end
private
def find(x)
return x if x == @par[x]
return @par[x] = find(@par[x])
end
public
def unite(x, y)
x = find(x)
y = find(y)
return nil if x == y
x, y = y, x if @size[x] < @size[y]
@par[y] = x
@size[x] += @size[y]
end
def same?(x, y)
return find(x) == find(y)
end
def size(x)
return @size[find(x)]
end
end
u = UnionFindTree.new
(10**5).times do |i|
u.unite(rand(10**9), rand(10**9))
end
(10**5).times do |i|
u.same?(i,i+1)
end