Pagini recente » Cod sursa (job #2719861) | Cod sursa (job #1527164) | Cod sursa (job #2580847) | Cod sursa (job #29459) | Cod sursa (job #2535494)
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))