Cod sursa(job #2946018)

Utilizator CornelProgramatorMarin Florin Eduard Marian CornelProgramator Data 24 noiembrie 2022 14:34:34
Problema Paduri de multimi disjuncte Scor 0
Compilator py Status done
Runda Arhiva educationala Marime 1.27 kb
input_file = open("disjoint.in",'r')
output_file = open("disjoint.out", 'w')


nr_sets,nr_op = [int(x) for x in input_file.readline().split()]

fatha = [0 for index_set in range(nr_sets+1)]
h = [0 for elem in fatha]
'''
def interog(x):
    if fatha[x] == 0:
        return x
    fatha[x] = interog(fatha[x])
    return fatha[x]
'''
def interog(x):
    if fatha[x] == 0:
        return x
    root = x
    while(fatha[root] != 0):
        root = fatha[root]
    
    index = x
    while(fatha[index] != 0):
        c_fatha = fatha[index]
        fatha[index] = root
        index = c_fatha
    return root

def reunion(x,y):
    repr_x = interog(x)
    repr_y = interog(y)
    if h[repr_x] == h[repr_y]:
        h[repr_x] += 1
        fatha[repr_y] = repr_x
    elif h[repr_x] > h[repr_y]:
        fatha[repr_y] = repr_x
    else:
        fatha[repr_x] = repr_y
def op1(x,y):
    reunion(x,y)
def op2(x,y):
    if interog(x) == interog(y):
        return "Da"
    return "Nu"

for op_index in range(nr_op):
    type_op,x,y = [int(elem) for elem in input_file.readline().split()]
    print(fatha)
    print(h)
    print(type_op,x,y)
    if type_op == 1:
        op1(x,y)
    else:
        print(op2(x,y))
        output_file.write(op2(x,y)+"\n")