while(n,m=gets.split.map &:to_i)[0]>0
c=(1..n).map{{}}
m.times{a,b,t=gets.split.map &:to_i;c[a][b]=c[b][a]=t}
d=[s=0]
(y,z=d.flat_map{|i|[*c[i].select{|k,v|d-[k]==d}]}.min_by{|k,v|v};s+=z;d<<y)while[*0..n-1]!=d.sort
p s
end