summaryrefslogtreecommitdiff
path: root/kattis-open-almostunionfind/bad.py
blob: 1d4cbec282988f73acb513785998b0bc465f3e74 (plain) (blame)
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
#!/usr/bin/python

while True:
    try:
        line = input()
    except EOFError:
        break
    n, m = map(int, line.split())

    u = [[i + 1] for i in range(n)]

    for _ in range(m):
        line = input().split()
        p = int(line[1])
        if line[0] != '3':
            q = int(line[2])

        if line[0] == '1': # union
            a, b = False, False
            for s in u:
                if p in s:
                    a = s
                if q in s:
                    b = s
            if a == False or b == False:
                raise ValueError(f"could not find {p} or {q} in {u}")
            if a != b:
                for i in b:
                    a.append(i)
                b.clear()
                u.remove(b)
        elif line[0] == '2': # move
            a, b = False, False
            for s in u:
                if p in s:
                    a = s
                if q in s:
                    b = s
            if a == False or b == False:
                raise ValueError(f"could not find {p} or {q} in {u}")
            if a != b:
                a.remove(p)
                b.append(p)
                if not a:
                    u.remove(a)
        elif line[0] == '3':
            for s in u:
                if p in s:
                    print(len(s), sum(s))
                    break
            else:
                raise ValueError(f"could not find {p} in {u}")
        # print(u)