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

x1 y1 z1 r1

x2 y2 z2 r2

...

xn yn zn rn

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



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


Sample output:
20.000
0.000
73.834

Submission status: Accepted

Solution code:
from decimal import Decimal, getcontext
from itertools import combinations
from heapq import *


getcontext().prec = 30

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 False
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        return True

while True:
    N = int(input())
    if N ==0:
        exit()

    tree = UnionFind(N)

    pos = dict()
    for i in range(N):
        pos[i] = tuple(map(Decimal, input().split()))

    data = []

    for a,b in combinations(range(N), 2):
        x1,x2,x3,xr = pos[a]
        y1,y2,y3,yr = pos[b]
        cost = max(((x1-y1)**2 + (x2-y2)**2 + (x3-y3)**2).sqrt() -xr -yr, 0)
        data.append((a, b, cost))

    res = 0
    data.sort(key=lambda x: x[2])

    for a, b, cost in data:
        if tree.union(a,b):
            res += cost
    print("{:.03f}".format(res))

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127

from decimal import Decimal, getcontext
from itertools import combinations
from heapq import *


getcontext().prec = 30

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 False
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        return True

while True:
    N = int(input())
    if N ==0:
        exit()

    tree = UnionFind(N)

    pos = dict()
    for i in range(N):
        pos[i] = tuple(map(Decimal, input().split()))

    data = []

    for a,b in combinations(range(N), 2):
        x1,x2,x3,xr = pos[a]
        y1,y2,y3,yr = pos[b]
        cost = max(((x1-y1)**2 + (x2-y2)**2 + (x3-y3)**2).sqrt() -xr -yr, 0)
        data.append((a, b, cost))

    res = 0
    data.sort(key=lambda x: x[2])

    for a, b, cost in data:
        if tree.union(a,b):
            res += cost
    print("{:.03f}".format(res))

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127
# クラスカル or プリム法

import math


class UnionFind:
    def __init__(self, n):
        self.n = n
        # 各要素の親要素の番号を格納するリスト
        # 根がルートの時は、グループの要素数を格納　最初は全て根で要素数1
        self.parents = [-1] * n

    # 再帰 groupの根を返す
    # 経路圧縮あり
    def find(self, x):
        # 0より小さい場合は根
        if self.parents[x] < 0:
            # indexを返す
            return x
        else:
            # 根になるまで親を辿る
            # 経路圧縮 根のindexが全ての親に再帰的につく
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    # groupを併合
    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
        # 根のグループ数を追加 xの方グループの要素数が多い前提なので多い方に寄せる
        self.parents[x] += self.parents[y]
        # 親(根)のindexを入れる
        self.parents[y] = x

    # xのgroupのサイズ
    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())

    # {root: [要素]}
    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())


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

    edge = []
    for i in range(n):
        for j in range(i + 1, n):
            dis = math.sqrt(
                (cell[i][0] - cell[j][0]) ** 2 + (cell[i][1] - cell[j][1]) ** 2 + (cell[i][2] - cell[j][2]) ** 2)
            #print(dis)
            if dis < (cell[i][3] + cell[j][3]):
                uf.union(i, j)
            else:
                edge.append((dis - (cell[i][3] + cell[j][3]), i, j))
    edge.sort()
    ans = 0
    num = n
    for c, a, b in edge:
        # 同じグループでなかったら統合
        if not uf.same(a, b):
            uf.union(a, b)
            ans += c
            num -= 1
            # グループ数は開催する都市の数になったら終了
            if num == 1:
                break
    print('{:.3f}'.format(ans))

Submission status: Accepted

Solution code:
import heapq
import math
from itertools import combinations


class UnionFind:
    from collections import deque

    def __init__(self, v):
        self.v = v
        self._tree = list(range(v + 1))

    def _root(self, a):
        queue = self.deque()
        while self._tree[a] != a:
            queue.append(a)
            a = self._tree[a]
        while queue:
            index = queue.popleft()
            self._tree[index] = a
        return a

    def union(self, a, b):
        root_a = self._root(a)
        root_b = self._root(b)
        self._tree[root_b] = root_a

    def find(self, a, b):
        return self._root(a) == self._root(b)


while True:
    N = int(input())

    if N == 0:
        break

    V = [tuple(map(float, input().split(' '))) for _ in range(N)]
    E = []
    for i, j in combinations(range(N), r=2):
        xi, yi, zi, ri = V[i]
        xj, yj, zj, rj = V[j]
        d = math.sqrt((xi - xj) ** 2 + (yi - yj) ** 2 + (zi - zj) ** 2)
        c = max(0.0, d - ri - rj)
        heapq.heappush(E, (c, i, j))

    uf = UnionFind(N)
    cost = 0.0
    while E:
        c, i, j = heapq.heappop(E)
        if not uf.find(i, j):
            uf.union(i, j)
            cost += c

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

Submission status: Accepted

Solution code:
from heapq import heappush, heappop


class UnionFind():
    def __init__(self, n):
        self.parents = list(range(n))

    def find(self, x):
        if self.parents[x] == x:
            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:
            self.parents[y] = x

while 1:
    N = int(input())
    if N == 0:
        exit()
    q = []
    ans = 0
    S = UnionFind(N)
    x = [None] * N
    y = [None] * N
    z = [None] * N
    r = [None] * N

    for i in range(N):
        x[i], y[i], z[i], r[i] = map(float, input().split())

    for i in range(N):
        for j in range(i+1, N):
            d = (x[i]-x[j])**2 + (y[i]-y[j])**2 + (z[i]-z[j])**2
            d = d**0.5 - r[i] - r[j]
            heappush(q, (max(0,d), i, j))
    # クラスカル法
    while len(q) > 0:
        d, a, b = heappop(q)
        if S.find(a) != S.find(b):
            ans += d
            S.union(a, b)
    print('{:.3f}'.format(ans))

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
# http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1127
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)]
        # 集団の要素数(size)を格納する(初期は全て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])
  
    # 結合(unite)する関数
    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:
    	# s, tが連結なら閉路を作ってしまう。
    	if uf.is_same(s, t):
        	    continue
    	# s, tを繋げても閉路にならないとき
    	else:
        	weight += w
        	uf.unite(s, t)

    return weight


def main():
    ans = []
    #with open("AOJ\\in.txt", "r") as f:

    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()

Submission status: Accepted

Solution code:
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])
            # print(n, edge)
            mst_cost = kruskal(edge, n)
            print(f'{mst_cost:.03f}')

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
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 #True:不使用
    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)

Submission status: Accepted

Solution code:
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}")

Submission status: Accepted

Solution code:
import sys
import copy
import heapq
from collections import deque
import decimal

# sys.setrecursionlimit(100001)
INF = sys.maxsize


# ===CODE===
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))


# ===main===
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
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

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
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):  # digitは小数何桁まで表示するか。 >= 0
    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))

Submission status: Accepted

Solution code:
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))