complete 1197.py 1717.py
This commit is contained in:
50
zeta_python/completed/1197.py
Normal file
50
zeta_python/completed/1197.py
Normal file
@@ -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))
|
||||||
@@ -1,26 +1,32 @@
|
|||||||
import sys
|
import sys
|
||||||
|
|
||||||
input = sys.stdin.readline
|
input = sys.stdin.readline
|
||||||
|
print = sys.stdout.write
|
||||||
|
|
||||||
|
|
||||||
def root(P, e):
|
def root(P, e):
|
||||||
node = e
|
node = e
|
||||||
while node != P[e]:
|
while node != P[node]:
|
||||||
node = P[e]
|
node = P[node]
|
||||||
return node
|
return node
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
N, M = map(int, input().split())
|
N, M = map(int, input().split())
|
||||||
P = [i for i in range(N + 1)]
|
P = [i for i in range(N + 1)]
|
||||||
|
|
||||||
for _ in range(M):
|
for _ in range(M):
|
||||||
op, a, b = map(int, input().split())
|
op, a, b = map(int, input().split())
|
||||||
if op == 0: # Merge
|
if op == 0: # Merge
|
||||||
if a == b:
|
if a == b:
|
||||||
continue
|
continue
|
||||||
rb, ra = root(P, b), root(P, a)
|
rb, ra = root(P, b), root(P, a)
|
||||||
if rb != ra:
|
|
||||||
|
if ra < rb:
|
||||||
P[rb] = ra
|
P[rb] = ra
|
||||||
print(P)
|
elif ra > rb:
|
||||||
|
P[ra] = rb
|
||||||
|
|
||||||
elif op == 1: # Find
|
elif op == 1: # Find
|
||||||
print("YES" if a == b or root(P, a) == root(P, b) else "NO")
|
print("YES" if a == b or root(P, a) == root(P, b) else "NO")
|
||||||
|
print("\n")
|
||||||
Reference in New Issue
Block a user