-
Notifications
You must be signed in to change notification settings - Fork 0
/
almost_union_find.py
71 lines (48 loc) · 1.38 KB
/
almost_union_find.py
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
59
60
61
62
63
64
65
66
67
68
69
70
71
import math
import queue
def join(x, y, roots, sets):
rX, rY = roots[x], roots[y]
if rX == rY:
return
if len(sets[rX]) >= len(sets[rY]):
for i in sets[rY]:
sets[rX].add(i)
roots[i] = rX
sets[rY] = set()
else:
for i in sets[rX]:
sets[rY].add(i)
roots[i] = rY
sets[rX] = set()
def mX_Y(x, y, roots, sets):
rX, rY = roots[x], roots[y]
if rX == rY:
return
sets[rX].remove(x)
sets[rY].add(x)
roots[x] = rY
def gSum(x, roots, sets):
return sum(sets[roots[x]])
def gSize(x, roots, sets):
return len(sets[roots[x]])
def main():
while True:
try:
n, m = (int(x) for x in input().split())
roots = [i for i in range(n+1)]
sets = [{i} for i in range(n+1)]
for _ in range(m):
inpoo = [int(x) for x in input().split()]
if len(inpoo) == 2:
x = int(inpoo[1])
print(f'{gSize(x, roots, sets)} {gSum(x, roots, sets)}')
else:
op, x, y = inpoo
if op == 1:
join(x, y, roots, sets)
else:
mX_Y(x, y, roots, sets)
except EOFError:
break
# print(roots, sets)
main()