Created
November 29, 2020 00:21
-
-
Save marianabianca/9bf64868c4e54e593eca9ce792e25119 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from queue import PriorityQueue | |
def find(x): | |
p = pai[x] | |
while x != p: | |
pai[x] = pai[p] | |
x = p | |
p = pai[p] | |
return p | |
def join(x, y): | |
pai[find(x)]=find(y) | |
while True: | |
cidades, caminhos = list(map(int, input().split())) | |
if cidades == 0 and caminhos == 0: break | |
pai = [i for i in range(cidades+1)] | |
pilha = PriorityQueue() | |
conectados = 0 | |
total = 0 | |
for i in range(caminhos): | |
a, b, p = list(map(int, input().split())) | |
pilha.put((p, min(a,b), max(a,b))) | |
while not pilha.empty() and conectados <= cidades: | |
p, a, b = pilha.get() | |
if find(a) != find(b): | |
join(a,b) | |
conectados += 1 | |
total += p | |
print(total) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment