Problem:
Building a Space Station You are a member of the space station engineering team,
and are assigned a task in the construction process of the station.
You are expected to write a computer program to complete the task. The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessarily uniform.
Each cell is fixed at its predetermined position
shortly after the station is successfully put into its orbit.
It is quite strange that two cells may be touching each other,
or even may be overlapping.
In an extreme case, a cell may be totally enclosing another one.
I do not know how such arrangements are possible. All the cells must be connected,
since crew members should be able to walk
from any cell to any other cell.
They can walk from a cell A to another cell B, if,
(1) A and B are touching each other or overlapping,
(2) A and B are connected by a `corridor',
or (3) there is a cell C such that walking from A to C, and also from B to C
are both possible.
Note that the condition (3) should be interpreted transitively. You are expected to design a configuration,
namely, which pairs of cells are to be connected with corridors.
There is some freedom in the corridor configuration.
For example, if there are three cells A, B and C,
not touching nor overlapping each other,
at least three plans are possible in order to connect all three cells.
The first is to build corridors A-B and A-C,
the second B-C and B-A, the third C-A and C-B.
The cost of building a corridor is proportional to its length.
Therefore, you should choose a plan with the shortest
total length of the corridors. You can ignore the width of a corridor.
A corridor is built between points on two cells' surfaces.
It can be made arbitrarily long, but of course the shortest one is chosen.
Even if two corridors A-B and C-D intersect in space, they are
not considered to form a connection path between (for example) A and C.
In other words, you may consider that two corridors never intersect. Input The input consists of multiple data sets.
Each data set is given in the following format.  n  x 1  y 1  z 1  r 1  x 2  y 2  z 2  r 2 ...  x n  y n  z n  r n  The first line of a data set contains an integer n ,
which is the number of cells. n is positive, and does not exceed 100. The following n lines are descriptions of cells.
Four values in a line are x- , y- and z- coordinates of
the center, and radius (called r in the rest of the problem) of
the sphere, in this order.
Each value is given by a decimal fraction, with
3 digits after the decimal point.
Values are separated by a space character. Each of x , y , z and r is positive
and is less than 100.0. The end of the input is indicated by a line containing a zero. Output For each data set, the shortest total length of the corridors
should be printed, each in a separate line.
The printed values should have 3 digits after the decimal point.
They may not have an error greater than 0.001. Note that if no corridors are necessary, that is,
if all the cells are connected without corridors,
the shortest total length of the corridors is 0.000. Sample Input 3
10.000 10.000 50.000 10.000
40.000 10.000 50.000 10.000
40.000 40.000 50.000 10.000
2
30.000 30.000 30.000 20.000
40.000 40.000 40.000 20.000
5
5.729 15.143 3.996 25.837
6.013 14.372 4.818 10.671
80.115 63.292 84.477 15.120
64.095 80.924 70.029 14.881
39.472 85.116 71.369 5.553
0 Output for the Sample Input 20.000
0.000
73.834

Solution (Python):
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]


from itertools import permutations
from math import sqrt
import heapq
while 1:
    N = int(input())
    if N==0:
        break
    uf = UnionFind(N)
    Vs = [list(map(float, input().split())) for _ in range(N)]
    lis = [i for i in range(N)]
    Edges = []
    for a, b in permutations(lis, 2):
        x1, y1, z1, r1 = Vs[a]
        x2, y2, z2, r2 = Vs[b]
        d = max(0, sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)-r1-r2)
        Edges.append((d, a, b))
    heapq.heapify(Edges)
    ans = 0
    while Edges:
        d, a, b = heapq.heappop(Edges)
        if not uf.same(a, b):
            ans += d
            uf.union(a, b)
    print('{:.3f}'.format(ans))

Solution (Python):
import math

while True:
    n=int(input())
    if n==0:
        break
    G=[]
    for index in range(n):
        x,y,z,r=map(float,input().split())
        G.append((x,y,z,r))

    def distance(X,Y):
        d=(X[0]-Y[0])**2+(X[1]-Y[1])**2+(X[2]-Y[2])**2
        Max=X[3]+Y[3]
        if Max**2<d:
            return math.sqrt(d)-Max    
        else:
            return 0
    
    D=[[0]*n for _ in range(n)]
    
    for index1 in range(n):
        for index2 in range(index1+1,n):
            dist=distance(G[index1],G[index2])
            D[index1][index2]=dist
            D[index2][index1]=dist

    def prim(n,cost):
        mincost = [float("inf")]*n
        used = [False] * n
        mincost[0] = 0
        res = 0

        while True:
            v = -1
            for i in range(n):
                if (not used[i]) and (v == -1 or mincost[i] < mincost[v]):
                    v = i
            if v == -1:
                break
            used[v] = True
            res += mincost[v]
            for i in range(n):
                mincost[i] = min(mincost[i],cost[v][i])
        return res
    

    ans=prim(n,D)
    print('{:.3f}'.format(ans))

Solution (Python):
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n)]
        self.rank = [0] * n
        self.size = [1] * n

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
    
    def same(self, x, y):
        if self.find(x) == self.find(y):
            return True
        else:
            return False


def kruskal(n, edges):
    uf = UnionFind(n)
    edges.sort()
    res = 0
    for c, s, t in edges:
        if not uf.same(s, t):
            res += c
            uf.unite(s, t)
    return res

while True:
    n = int(input())
    if n == 0: break

    x = [0] * n
    y = [0] * n
    z = [0] * n
    r = [0] * n
    for i in range(n):
        x[i], y[i], z[i], r[i] = map(float, input().split())
    
    edges = []
    for i in range(n):
        for j in range(n):
            if i == j: continue
            c = max(((x[i]-x[j])**2 + (y[i]-y[j])**2 + (z[i]-z[j])**2)**(1/2) - (r[i]+r[j]), 0)
            edges.append((c, i, j))
    
    print("{:.3f}".format(kruskal(n, edges)))

Solution (Python):

from math import sqrt
import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

class UnionFind:
    def __init__(self, n):
        
        self.par = [i for i in range(n+1)]
        
        self.size = [1] * (n+1)
    
    
    def find(self, x):
        
        if self.par[x] == x:
            return x
        
        else:
            
            self.par[x] = self.find(self.par[x])
            return self.find(self.par[x])
  
    
    def unite(self, x, y):
        
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        
        if self.size[x] < self.size[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
           
    
    def is_same(self, x, y):
        return self.find(x) == self.find(y)
    
    
    def get_size(self, x):
        return self.size[self.find(x)]
    
    
    def group_sum(self):
        c = 0
        for i in range(len(self.par)):
            if self.find(i) == i:
                c += 1
        return c
    

def Kruskal(V, Edges):
    """
    E: E[i] = (from, to, weight)として辺を格納したリスト
    """
    
    Edges.sort(key=lambda x: x[2])

    uf = UnionFind(V)
    weight = 0
    for s, t, w in Edges:
    	
    	if uf.is_same(s, t):
        	    continue
    	
    	else:
        	weight += w
        	uf.unite(s, t)

    return weight


def main():
    ans = []
    

    while True:
        n = int(readline())
        if n == 0:
            break
            
        xyzr = [tuple(map(float, readline().split()))for _ in range(n)]
        E = []
        for i in range(n-1):
            x_i, y_i, z_i, r_i = xyzr[i]
            for j in range(i+1,n):
                x_j, y_j, z_j, r_j = xyzr[j]
                d = sqrt((x_i - x_j)**2 + (y_i - y_j)**2 + (z_i - z_j)**2)
                length = max(d - (r_i + r_j), 0.0)
                E.append((i, j, length))

        
        weight = Kruskal(n, E)
        ans.append(weight)

    print("\n".join("{:.3f}".format(i) for i in ans))


if __name__ == "__main__":
    main()

Solution (Python):
import sys, itertools
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
MOD = 1000000007
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def same(self, x, y):
        return self.find(x) == self.find(y)

def kruskal(es, V):
    es.sort(key=lambda x:x[2])
    uf = UnionFind(V)
    res = 0
    for e in es:
        if not uf.same(e[0], e[1]):
            uf.union(e[0], e[1])
            res += e[2]
    return res

def resolve():
    while True:
        n = I()
        if n==0:
            break
        else:
            xyzr = [LF() for _ in range(n)]

            edge = []
            for i, j in itertools.combinations(range(n), 2):
                corridor_length = max(sum([(k-m)**2 for k, m in zip(xyzr[i][:3], xyzr[j][:3])])**0.5-(xyzr[i][3]+xyzr[j][3]), 0)
                edge.append([i, j, corridor_length])
            
            mst_cost = kruskal(edge, n)
            print(f'{mst_cost:.03f}')

if __name__ == '__main__':
    resolve()

Solution (Python):
import heapq
import math
def set_heapq(que, edge, used, v, add_dist=0):
    '''
    確定地点vからつながる辺を全てqueに設定し、返却する

    Parameters
    que : heapque(touple or list)
        辺を管理するキュー (距離、次の行き先)のtopuleまたはlistにて管理
    edge : list
        全ての辺を格納する二次元のリスト edge[0]にてノード0から伸びる辺であることを表し、
        edge[0] → [距離、次の行き先] を表すlistが格納されている
    v : int
        グラフ上のノード ダイクストラでは確定したノードがvにあたる
    add_dist : int
        確定した地点に足し合わせる距離 スタート地点以外では何かしらの値が追加されることになる

    Returns
    que : heapque(touple or list)
        引数queにvからつながる辺を追加したキュー
    '''
    for a,b in edge[v]:
        if used[b]:
            heapq.heappush(que,(a+add_dist,b))
    return que

def prim_heap(edge, n):
    '''
    プリム法で最小全域木を求める

    Parameters
    edge : list
        全ての辺を格納する二次元のリスト edge[0]にてノード0から伸びる辺であることを表し、
        edge[0] → [距離、次の行き先] を表すlistが格納されている
    
    Returns
    res : int
        最小全域木の全ての辺のコストの総和
    '''
    used = [True] * n 
    edgelist = []
    edgelist = set_heapq(edgelist, edge, used, 0)
    used[0] = False
    res = 0
    while len(edgelist) != 0:
        minedge = heapq.heappop(edgelist)
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        used[v] = False
        edgelist = set_heapq(edgelist, edge, used, v)
        res += minedge[0]
    return res

def write_file(s):
    with open("tmp.txt", "a") as f:
        f.write(s+"\n")

while True:
    N = int(input())
    if N == 0: break
    xyzr = [list(map(float, input().split())) for _ in range(N)]
    edge = [[] for _ in range(N)]
    
    for i in range(N):
        for j in range(i+1,N):
            x1,y1,z1,r1 = xyzr[i]
            x2,y2,z2,r2 = xyzr[j]
            dist = math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z1-z2)**2)
            dist = max(0, dist-r1-r2)
            edge[i].append((dist, j))
            edge[j].append((dist, i))
    ans = prim_heap(edge, N)
    ans = ('{:0.3f}'.format(ans))
    print(ans)

Solution (Python):
class DisjointSets:
    def __init__(self,n):
        self.parent = [i for i in range(n)]
        self.siz = [1]*n

    def root(self,x):
        if x != self.parent[x]: 
            self.parent[x] = self.root(self.parent[x])
        return self.parent[x]

    def same(self,x,y): 
        return self.root(x) == self.root(y)

    def unite(self,x,y): 
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        if self.siz[x] < self.siz[y]:
            x,y = y,x
        self.parent[y] = x
        self.siz[x] += self.siz[y]

    def size(self,x):
        return self.siz[self.root(x)]

def length(a,b):
    x1,y1,z1,r1 = cell[a]
    x2,y2,z2,r2 = cell[b]
    return ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5-r1-r2

while True:
    n = int(input())
    if not n: break
    cell = [[float(i) for i in input().split()] for _ in range(n)]
    corri = []
    ds = DisjointSets(n)
    for i in range(n):
        for j in range(i+1,n):
            l = length(i,j)
            if l <= 0: ds.unite(i,j)
            else: corri.append((l,i,j))
    corri.sort(key = lambda x:x[0])
    sumlen = 0
    for l,a,b in corri:
        if ds.same(a,b): continue
        sumlen += l
        ds.unite(a,b)
    print(f"{sumlen:.3f}")

Solution (Python):
import sys
import copy
import heapq
from collections import deque
import decimal


INF = sys.maxsize



def main():
    class UnionFind():
        def __init__(self, n):
            self.n = n
            self.parents = [-1] * n

        def find(self, x):
            if self.parents[x] < 0:
                return x
            else:
                self.parents[x] = self.find(self.parents[x])
                return self.parents[x]

        def union(self, x, y):
            x = self.find(x)
            y = self.find(y)

            if x == y:
                return

            if self.parents[x] > self.parents[y]:
                x, y = y, x

            self.parents[x] += self.parents[y]
            self.parents[y] = x

        def size(self, x):
            return -self.parents[self.find(x)]

        def same(self, x, y):
            return self.find(x) == self.find(y)

        def members(self, x):
            root = self.find(x)
            return [i for i in range(self.n) if self.find(i) == root]

        def roots(self):
            return [i for i, x in enumerate(self.parents) if x < 0]

        def group_count(self):
            return len(self.roots())

        def all_group_members(self):
            return {r: self.members(r) for r in self.roots()}

        def __str__(self):
            return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

    def calc_dist(x1, y1, z1, r1, x2, y2, z2, r2):
        tmp = ((float(x1) - float(x2)) ** 2 + (float(y1) - float(y2)) ** 2 + (float(z1) - float(z2)) ** 2) ** (1 / 2)
        tmp = max(0, tmp - float(r1) - float(r2))
        return tmp

    while True:
        n = int(input())
        if n == 0:
            exit(0)
        tree = UnionFind(n)

        data = [input().split() for i in range(n)]

        edges = []
        for i in range(n):
            for j in range(i + 1, n):
                edges.append((calc_dist(data[i][0], data[i][1], data[i][2], data[i][3], data[j][0], data[j][1],
                                        data[j][2], data[j][3]), i, j))

        edges.sort()

        ans = 0
        for d, s, t in edges:
            if not tree.same(s, t):
                tree.union(s, t)
                ans += d

        print("{:.3f}".format(ans))



if __name__ == '__main__':
    main()

Solution (Python):

from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def root(x):
        if par[x] == x:
            return x
        par[x] = root(par[x])
        return par[x]

    def unite(x,y):
        x = root(x)
        y = root(y)
        if x == y:
            return
        if rank[x] < rank[y]:
            par[x] = y
        else:
            par[y] = x
            if rank[x] == rank[y]:
                rank[x] += 1

    def D2(i,j):
        x1,y1,z1,r = p[i]
        x2,y2,z2,r = p[j]
        return (x1-x2)**2+(y1-y2)**2+(z1-z2)**2

    while 1:
        n = I()
        if n == 0:
            return
        p = [list(map(float, input().split())) for i in range(n)]
        d2 = [[D2(i,j) for j in range(i)] for i in range(n)]
        par = [i for i in range(n)]
        rank = [0]*n
        v = []
        for i in range(n):
            x,y,z,r1 = p[i]
            for j in range(i):
                x,y,z,r2 = p[j]
                d = r1+r2
                d2ij = d2[i][j]
                if d2ij > d**2:
                    v.append((d2ij**0.5-d,i,j))
                else:
                    unite(i,j)
        v.sort()
        ans = 0.0
        for c,a,b in v:
            if root(a) != root(b):
                ans += c
                unite(a,b)
        print("{:.3f}".format(round(ans,3)))
    return


if __name__ == "__main__":
    solve()

Solution (Python):
import sys
import math
import string
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = float('inf')
input = lambda: sys.stdin.readline().strip()


def minimum_spanning_tree(n, info):
    """
    頂点の数:nと辺の情報i:infoから最小全域木([[辺の始点の頂点,辺の終点の頂点, 重み], ...])を返す。
    info:[[辺の始点の頂点,辺の終点の頂点, 重み], ...](bellman_ford()の入力形式)
    """
    ans = []
    info.sort(key=itemgetter(2))

    class UnionFind:
        def __init__(self, n):
            self.n = n
            self.parents = [-1] * n

        def find(self, x):
            if self.parents[x] < 0:
                return x
            else:
                self.parents[x] = self.find(self.parents[x])
                return self.parents[x]

        def union(self, x, y):
            x = self.find(x)
            y = self.find(y)

            if x == y:
                return

            if self.parents[x] > self.parents[y]:
                x, y = y, x

            self.parents[x] += self.parents[y]
            self.parents[y] = x

        def size(self, x):
            return -self.parents[self.find(x)]

        def same(self, x, y):
            return self.find(x) == self.find(y)

        def members(self, x):
            root = self.find(x)
            return [i for i in range(self.n) if self.find(i) == root]

        def roots(self):
            return [i for i, x in enumerate(self.parents) if x < 0]

        def group_count(self):
            return len(self.roots())

        def all_group_members(self):
            return {r: self.members(r) for r in self.roots()}

        def __str__(self):
            return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

    uf = UnionFind(n)
    for i in info:
        if not uf.same(i[0], i[1]):
            ans.append(i)
            uf.union(i[0], i[1])
    return ans


def digit_print(num, digit):  
    if digit == 0:
        if type(num) is int:
            return num
        else:
            num = str(num)
            return num[:num.index(".")]
    else:
        if type(num) is int:
            return str(num) + "." + "0" * digit
        else:
            num = str(num) + "0" * digit
            return num[:num.index(".") + digit + 1]


while True:
    n = int(input())
    if n == 0:
        break
    x_y_z_r_num = [list(map(float, input().split())) + [i] for i in range(n)]
    info = []
    for i in itertools.combinations(x_y_z_r_num, 2):
        dis = math.sqrt(sum((px - qx) ** 2.0 for px, qx in zip(i[0][:3], i[1][:3])))
        if i[0][3] + i[1][3] >= dis:
            info.append([i[0][4], i[1][4], 0.00])
        else:
            info.append([i[0][4], i[1][4], dis - i[0][3] - i[1][3]])
    print(digit_print(round(sum(i[2] for i in minimum_spanning_tree(n, info)), 3), 3))

Solution (Python):
import queue, math
while True:
    n = int(input())
    if n == 0: break
    p = [[float(x) for x in input().split()] for _ in range(n)]
    g = [i for i in range(n)]

    def root(x):
        if x == g[x]: return x
        g[x] = root(g[x])
        return g[x]

    q = queue.PriorityQueue()
    cnt_g = n
    ans = 0.0
    for i in range(n-1):
        for j in range(i,n):
            d = math.sqrt((p[i][0]-p[j][0])**2 + (p[i][1]-p[j][1])**2 + (p[i][2]-p[j][2])**2)
            if d <= p[i][3] + p[j][3] :
                if root(i) != root(j):
                    g[root(i)] = root(j)
                    cnt_g -= 1
            else:
                q.put((d-p[i][3]-p[j][3],i,j))

    while not q.empty():
        if cnt_g <= 1 : break
        d, i, j = q.get()
        if root(i) != root(j):
            g[root(i)] = root(j)
            cnt_g-= 1
            ans += d

    print ('{:.3f}'.format(ans))

Solution (Python):
from math import sqrt
import heapq


import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline


class UnionFind:
    """
    sizeによる実装
    """

    def __init__(self, N):
        self.parent = [i for i in range(N)]
        self.size = [1 for _ in range(N)]

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            return self.find(self.parent[x])

    def union(self, x, y):
        px = self.find(x)
        py = self.find(y)
        if px == py:
            return
        if self.size[px] < self.size[py]:
            self.parent[px] = py
            self.size[py] += self.size[px]
        else:
            self.parent[py] = px
            self.size[px] += self.size[py]

    def same(self, x, y):
        return self.find(x) == self.find(y)


def calc_dist(s1, s2):
    dist = sqrt(sum([abs(a-b)**2 for a, b in zip(s1[:-1], s2[:-1])]))
    return max(dist-s1[3] - s2[3], 0)


def solve():
    N = int(input())
    if N == 0:
        exit()
    spheres = [list(map(float, input().split())) for _ in range(N)]
    dists = []
    Un = UnionFind(N)
    for i in range(N):
        for j in range(i+1, N):
            tmp = calc_dist(spheres[i], spheres[j])
            
            heapq.heappush(dists, [tmp, i, j])

    cost = 0
    
    for k in range(len(dists)):
        dist, i, j = heapq.heappop(dists)
        if Un.same(i, j):
            continue
        else:
            Un.union(i, j)
            cost += dist
    print("{:.3f}".format(cost))


while True:
    solve()