Cod sursa(job #2449564)

Utilizator voyagerSachelarie Bogdan voyager Data 20 august 2019 02:39:49
Problema Paduri de multimi disjuncte Scor 10
Compilator py Status done
Runda Arhiva educationala Marime 0.75 kb
#!/usr/bin/env python3

import sys
sys.stdout = open('disjoint.out', 'w')

with open('disjoint.in', 'r') as f:
    readInts = lambda: tuple(map(int, f.readline().split()))

    N, M = readInts()
    P, RNK = list(range(N)), [1] * N

    def find(a):
        root = a
        while P[root] != root:
            root = P[root]
        while a != root:
            a, P[a] = P[a], root
        return root

    def unite(a, b):
        if RNK[a] > RNK[b]:
            P[b] = P[a]
        else:
            P[a] = P[b]
        if RNK[a] == RNK[b]:
            RNK[b] += 1

    for _ in range(M):
        op, a, b = readInts()
        a, b = a - 1, b - 1

        if op == 1:
            unite(a, b)
        else:
            print('DA' if find(a) == find(b) else 'NU')