Cod sursa(job #2535494)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 31 ianuarie 2020 22:02:43
Problema Paduri de multimi disjuncte Scor 40
Compilator py Status done
Runda Arhiva educationala Marime 1.19 kb
def read_gen(fname):
    with open(fname, 'rt') as fin:
        for line in fin:
            for val in line.split():
                yield int(val)

def get_root(parent, x):
    if parent[x] == x:
        return x
    else:
        root = get_root(parent, parent[x])
        parent[x] = root
        return root

def unite(h, parent, x, y):
    root_x = get_root(parent, x)
    root_y = get_root(parent, y)
    if root_x != root_y:
        if h[root_x] > h[root_y]:
            parent[rooy_x] = root_y
            h[root_x] = max(h[root_x], h[root_y] + 1)
        else:
            parent[root_y] = root_x
            h[root_y] = max(h[root_y], h[root_x] + 1)

if __name__ == "__main__":
    it = read_gen('disjoint.in')
    n, m = next(it), next(it)
    parent = {x: x for x in range(1, n + 1)}
    h = {x: 1 for x in range(1, n + 1)}

    with open('disjoint.out', 'wt') as fout:
        for _ in range(m):
            t, x, y = next(it), next(it), next(it)
            if t == 1:
                unite(h, parent, x, y)
            else:
                same_set = (get_root(parent, x) == get_root(parent, y))
                same_set = "DA" if same_set else "NU"
                fout.write("{}\n".format(same_set))