Skip to content

Instantly share code, notes, and snippets.

@marianabianca
Created November 29, 2020 00:21
Show Gist options
  • Save marianabianca/9bf64868c4e54e593eca9ce792e25119 to your computer and use it in GitHub Desktop.
Save marianabianca/9bf64868c4e54e593eca9ce792e25119 to your computer and use it in GitHub Desktop.
# 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