python实现的prim算法求MST O(MN)

n,m = [int(x) for x in raw_input().split()]
use = range(500)
edge = []
for i in range(m):
	v1,v2,ecost = [int(x) for x in raw_input().split()]
	v1 -= 1
	v2 -= 1
	edge.append((v1,v2,ecost))
for i in range(len(use)):
	use[i] = 0
use[0] = 1
cost = 0
for i in range(n-1):
	mincost = (0,0,999999999)
	for j in edge :
		if use[j[0]]+use[j[1]] == 1 and mincost[2] > j[2] :
			mincost = j
	print mincost	
	cost += mincost[2]
	if use[mincost[0]] == 0 :
		use[mincost[0]] = 1
	else :
		use[mincost[1]] = 1

print cost

你可能感兴趣的:(python实现的prim算法求MST O(MN))