From 22701fa975e56f0376e166ac2401584be96b9b3c Mon Sep 17 00:00:00 2001 From: yenru0 Date: Mon, 30 Sep 2024 09:39:16 +0900 Subject: [PATCH] complete 1197.py 1717.py --- zeta_python/completed/1197.py | 50 +++++++++++++++++++++++++++++ zeta_python/{ => completed}/1717.py | 14 +++++--- 2 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 zeta_python/completed/1197.py rename zeta_python/{ => completed}/1717.py (73%) diff --git a/zeta_python/completed/1197.py b/zeta_python/completed/1197.py new file mode 100644 index 0000000..226684a --- /dev/null +++ b/zeta_python/completed/1197.py @@ -0,0 +1,50 @@ +import sys + +input = sys.stdin.readline + + +def find(P, a) -> int: + node = a + while node != P[node]: + node = P[node] + return node + + +def union(P, a, b) -> None: + ra = find(P, a) + rb = find(P, b) + if ra < rb: + P[rb] = ra + else: + P[ra] = rb + + +def two_of_them(P, a, b) -> bool: + return find(P, a) == find(P, b) + + +def get_MST(V, E, Es) -> int: + # sort Edges + Es.sort(key=lambda x: x[-1]) + + P = [i for i in range(V + 1)] + cum_edges = [] + for ei in range(E): + s, e, w = Es[ei] + if not two_of_them(P, s, e): + cum_edges.append(w) + union(P, s, e) + if len(cum_edges) == V - 1: + break + + return sum(cum_edges) + + +if __name__ == "__main__": + V, E = map(int, input().split()) + Es = [] + for _ in range(E): + start, end, weight = map(int, input().split()) + Es.append((start, end, weight)) + + print(get_MST(V, E, Es)) diff --git a/zeta_python/1717.py b/zeta_python/completed/1717.py similarity index 73% rename from zeta_python/1717.py rename to zeta_python/completed/1717.py index 43b7856..a46dad4 100644 --- a/zeta_python/1717.py +++ b/zeta_python/completed/1717.py @@ -1,26 +1,32 @@ import sys input = sys.stdin.readline +print = sys.stdout.write def root(P, e): node = e - while node != P[e]: - node = P[e] + while node != P[node]: + node = P[node] return node if __name__ == "__main__": N, M = map(int, input().split()) P = [i for i in range(N + 1)] + for _ in range(M): op, a, b = map(int, input().split()) if op == 0: # Merge if a == b: continue rb, ra = root(P, b), root(P, a) - if rb != ra: + + if ra < rb: P[rb] = ra - print(P) + elif ra > rb: + P[ra] = rb + elif op == 1: # Find print("YES" if a == b or root(P, a) == root(P, b) else "NO") + print("\n")