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: Wrong Answer

Solution code:
inf = 1 << 28
def calc(xyzr1,xyzr2):
    x1,y1,z1,r1 = xyzr1
    x2,y2,z2,r2 = xyzr2
    d = ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5
    return max(0, d-r1-r2)
    
while 1:
    n = int(raw_input())
    if n == 0: break
    xyzr = [map(float,raw_input().split()) for i in xrange(n)]
    
    cost = [[0]*n for i in xrange(n)]
    for i in xrange(n):
        for j in xrange(n):
            cost[i][j] = cost[j][i] = calc(xyzr[i],xyzr[j])
    
    mincost = [inf]*n
    used = [False]*n
    mincost[0] = 0
    ans = 0
    while 1:
        v = -1
        for u in xrange(n):
            if not used[u] and (v == -1 or mincost[u] < mincost[v]): v = u
        if v == -1: break
        used[v] = True
        ans += mincost[v]
        for u in xrange(n):
            mincost[u] = min(mincost[u], cost[v][u])
    
    print "%.6f"%ans

Submission status: Wrong Answer

Solution code:
while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	ans = 0
	chain = [xyzr.pop(0)]
	while xyzr:
		pipe = 1e10
		for i in range(len(xyzr)):
			x,y,z,r = xyzr[i]
			for j in range(len(chain)):
				x1,y1,z1,r1 = chain[j]
				l = max(0,((x-x1)**2 + (y-y1)**2 + (z-z1)**2)**0.5 - r - r1)
				if l < pipe:
					pipe = l
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	ans = 0.0
	chain = [xyzr.pop(0)]
	while xyzr:
		pipe = 1e12
		for i in range(len(xyzr)):
			x,y,z,r = xyzr[i]
			for j in range(len(chain)):
				x1,y1,z1,r1 = chain[j]
				l = max(0,((x-x1)**2 + (y-y1)**2 + (z-z1)**2)**0.5 - r - r1)
				if l < pipe:
					pipe = l
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
from math import *
while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	ans = 0.0
	chain = [xyzr.pop(0)]
	while xyzr:
		pipe = 1e12
		for i in range(len(xyzr)):
			x,y,z,r = xyzr[i]
			for j in range(len(chain)):
				x1,y1,z1,r1 = chain[j]
				l = max(0,sqrt((x-x1)**2 + (y-y1)**2 + (z-z1)**2) - r - r1)
				if l <= pipe:
					pipe = l
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
def R(xyzr1,xyzr2):
	x1,y1,z1,r1 = xyzr1
	x2,y2,z2,r2 = xyzr2
	return max(0,((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)**0.5 - r1 - r2)

while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
#	ans = 1e10
#	for i in range(n):
#		for j in range(i+1,n):
#			l = R(xyzr[i],xyzr[j])
#			if l < ans:
#				ans = l
#				s = [i,j]
	ans = 0.0
	chain = [xyzr.pop(0)] #[xyzr.pop(s[1]),xyzr.pop(s[0])]
	while xyzr:
		pipe = 1e10
		for i in range(len(xyzr)):
			for j in range(len(chain)):
				l = R(xyzr[i],chain[j])
				if l < pipe:
					pipe = l
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
def R(xyzr1,xyzr2):
	x1,y1,z1,r1 = xyzr1
	x2,y2,z2,r2 = xyzr2
	return max(0,((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)**0.5 - r1 - r2)

while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	ans = 1e10
	for i in range(n):
		for j in range(i+1,n):
			l = R(xyzr[i],xyzr[j])
			if l < ans:
				ans = l
				s = [i,j]
	ans = 0.0
	chain = [xyzr.pop(0)] #[xyzr.pop(s[1]),xyzr.pop(s[0])]
	while xyzr:
		pipe = 1e10
		for i in range(len(xyzr)):
			for j in range(len(chain)):
				l = R(xyzr[i],chain[j])
				if l < pipe:
					pipe = l
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
def R(xyzr1,xyzr2):
	x1,y1,z1,r1 = xyzr1
	x2,y2,z2,r2 = xyzr2
	return max(0,((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)**0.5 - r1 - r2)
while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	l = 1e10
	s = 0
	for i in range(n):
		for j in range(i+1,n):
			L = R(xyzr[i],xyzr[j])
			if L < l:
				l = L
				s = i
	ans = 0.0
	chain = [xyzr.pop(s)]
	while xyzr:
		pipe = 1e10
		for i in range(len(xyzr)):
			for j in range(len(chain)):
				L = R(xyzr[i],chain[j])
				if L < pipe:
					pipe = L
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Wrong Answer

Solution code:
def R(xyzr1,xyzr2):
	x1,y1,z1,r1 = xyzr1
	x2,y2,z2,r2 = xyzr2
	return max(0,((x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2)**0.5 - r1 - r2)
while 1:
	n = input()
	if n == 0: break
	xyzr = [map(float,raw_input().split()) for i in range(n)]
	if n == 1:
		print 0.0
		continue
	ans = 1e10
	for i in range(n):
		for j in range(i+1,n):
			L = R(xyzr[i],xyzr[j])
			if L < ans:
				ans = L
				s = [i,j]
	chain = [xyzr.pop(s[1]),xyzr.pop(s[0])]
	while xyzr:
		pipe = 1e10
		for i in range(len(xyzr)):
			for j in range(len(chain)):
				L = R(xyzr[i],chain[j])
				if L < pipe:
					pipe = L
					p = i
		ans += pipe
		chain.append(xyzr.pop(p))
	print ans

Submission status: Accepted

Solution code:
inf = 1 << 28
def calc(xyzr1,xyzr2):
    x1,y1,z1,r1 = xyzr1
    x2,y2,z2,r2 = xyzr2
    d = ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5
    return max(0, d-r1-r2)
    
while 1:
    n = int(raw_input())
    if n == 0: break
    xyzr = [map(float,raw_input().split()) for i in xrange(n)]
    
    cost = [[0]*n for i in xrange(n)]
    for i in xrange(n):
        for j in xrange(n):
            cost[i][j] = cost[j][i] = calc(xyzr[i],xyzr[j])
    
    mincost = [inf]*n
    used = [False]*n
    mincost[0] = 0
    ans = 0
    while 1:
        v = -1
        for u in xrange(n):
            if not used[u] and (v == -1 or mincost[u] < mincost[v]): v = u
        if v == -1: break
        used[v] = True
        ans += mincost[v]
        for u in xrange(n):
            mincost[u] = min(mincost[u], cost[v][u])
    
    print "%.3f"%ans

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

class UnionFind:
    def __init__(self, size):
        self.table = [-1 for _ in range(size)]

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

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

    def subsetall(self):
        a = []
        for i in range(len(self.table)):
            if self.table[i] < 0:
                a.append((i, -self.table[i]))
        return a

def main():
    rr = []

    while True:
        n = I()
        if n == 0:
            break
        a = [LF() for _ in range(n)]
        e = []
        for i in range(n):
            for j in range(i+1,n):
                k = sum([(a[i][_]-a[j][_])**2 for _ in range(3)]) ** 0.5
                t = a[i][3] + a[j][3]
                e.append((k-t,i,j))
        e.sort()
        uf = UnionFind(n)
        r = 0
        for k,i,j in e:
            if uf.union(i,j):
                if k > 0:
                    r += k

        rr.append('{:0.3f}'.format(r))

    return '\n'.join(map(str,rr))


print(main())

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(100000)


class UnionFind:
    def __init__(self, n):
        super().__init__()
        self.par = [i for i in range(n + 1)]
        self.rank = [0 for i in range(n + 1)]

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

    def is_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:
            if self.rank[x] < self.rank[y]:
                self.par[x] = y
            elif self.rank[x] > self.rank[y]:
                self.par[y] = x
            else:
                self.par[x] = y
                self.rank[y] += 1


def distance(cell1, cell2):
    c_dis = 0
    for i in range(3):
        c_dis += (cell1[i] - cell2[i])**2
    c_dis = c_dis**(1 / 2) - (cell1[3] + cell2[3])
    return c_dis if c_dis > 0 else 0


while True:
    n = int(input())
    if n == 0:
        break
    union = UnionFind(n)
    cell_list = [list(map(float, input().split())) for i in range(n)]
    distance_list = []
    for i, b_cell in enumerate(cell_list):
        for j, cell in enumerate(cell_list[i + 1:]):
            distance_list.append([distance(b_cell, cell), i, i + 1 + j])

    distance_list.sort()
    total_dis = 0
    for dis in distance_list:
        if not union.is_same(dis[1], dis[2]):
            union.unite(dis[1], dis[2])
            total_dis += dis[0]

    print(format(total_dis, ".3f"))

Submission status: Accepted

Solution code:
# 66

from decimal import *
import heapq

class UnionFind:
    def __init__(self, n):
        self.rank = [1] * n
        self.par = [int(x) for x in range(n)]
        
    def find(self, x):
        if self.par[x] == x:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]
    
    def unite(self, x, y):
        p_x = self.find(x)
        p_y = self.find(y)
        if p_x == p_y:
            return False
        if self.rank[p_x] < self.rank[p_y]:
            self.par[p_x] = p_y
            self.rank[p_x] += 1
        else:
            self.par[p_y] = p_x
            self.rank[p_y] += 1
        return True
    
    def same(self, x, y):
        p_x = self.find(x)
        p_y = self.find(y)
        if p_x == p_y:
            return True
        else:
            return False
    
while True:
    N = int(input())
    if N == 0:
        exit(0)
    C_L = [[int(Decimal(x) * (10**3)) for x in input().split()] for y in range(N)]
    
    UF = UnionFind(N)
    hq = []
    for i in range(N):
        i_x, i_y, i_z, i_r = C_L[i]
        for j in range(i+1,N):
            j_x, j_y, j_z, j_r = C_L[j]
            _d = ((i_x - j_x)**2 + (i_y - j_y)**2 + (i_z - j_z)**2) ** (0.5) - i_r - j_r
            hq.append([_d, i, j])
#     print(hq)
#     print("HOGE")
    ans = 0
    heapq.heapify(hq)
    while len(hq) > 0:
        _d, _i, _j = heapq.heappop(hq)
        if UF.same(_i, _j):
            continue
        ans += max(_d, 0)
        UF.unite(_i, _j)
    print("{:.3f}".format(ans / (10**3)))

Submission status: Accepted

Solution code:
while True:
    N = int(input())
    if not N:
        break
    X = [False if i else True for i in range(N)]
    ans = 0

    V = [list(map(float, input().split())) for i in range(N)]
    dp = [[0 for i in range(N)] for j in range(N)]

    # とりあえずすべての変の距離を測る
    for i in range(N):
        for j in range(N):
            if i == j:
                dp[i][j] = float('inf')
            else:
                tmp = ((V[i][0] - V[j][0]) ** 2 + (V[i][1] - V[j][1]) ** 2 + (V[i][2] - V[j][2]) ** 2) ** 0.5
                dp[i][j] = max(0, tmp - V[i][3] - V[j][3])

    # おそらくプリム法
    for loop in range(N - 1):
        tmpmin = float('inf')
        for i in range(N):
            for j in range(N):
                if X[i] and not X[j]:
                    if dp[i][j] < tmpmin:
                        tmpmin = dp[i][j]
                        tmp = j
        ans += tmpmin
        X[tmp] = True

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
from heapq import heappop, heappush

def find(x):
    if x == pair_lst[x]:
        return x
    else:
        tmp = find(pair_lst[x])
        pair_lst[x] = tmp
        return tmp
x=[]
y=[]
z=[]
r=[]
def kr():
    que=[]
    for i in range(n-1):
        for j in range(i+1,n):
            wi=((x[i]-x[j])**2+(y[i]-y[j])**2+(z[i]-z[j])**2)**0.5
            wi=max(0,wi-r[i]-r[j])        
            heappush(que,(wi,i,j))
    length_sum = 0
    while que:
        w, s, t = heappop(que)
        root_s = find(s)
        root_t = find(t)
        if root_s != root_t:
            pair_lst[root_s] = root_t
            length_sum += w
    return length_sum

while True:
    n=int(input())
    x=[0.0]*n
    y=[0.0]*n
    z=[0.0]*n
    r=[0.0]*n
    pair_lst = [i for i in range(n)]
    
    if n==0:
        sys.exit()
    for i in range(n):
        x[i],y[i],z[i],r[i]=map(float,input().split())
    print("{:.3f}".format(kr()))

Submission status: Accepted

Solution code:
import heapq
import math

def dist(xyzr0, xyzr1):
    vec = [xyzr0[i] - xyzr1[i] for i in range(3)]
    d = math.sqrt(sum([elem*elem for elem in vec]))
    return max(0, d - xyzr0[3] - xyzr1[3])

def mst(n, dists):
    in_tree = [False] * n
    start = 0
    in_tree[start] = True
    q = [(dists[start][to], start, to) for to in range(n)]
    heapq.heapify(q)
    ans = 0
    cnt = 0
    while q and cnt < n-1:
        dist, fr, to = heapq.heappop(q)
        if in_tree[to]:
            continue
        in_tree[to] = True
        ans += dist
        cnt += 1
        for to_ in range(n):
            heapq.heappush(q, (dists[to][to_], to, to_))
    return ans

def solve(n):
    XYZR = []
    for _ in range(n):
        XYZR.append(list(map(float, input().split())))
    dists = [[0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            dists[i][j] = dist(XYZR[i], XYZR[j])
    ans = mst(n, dists)
    print('%.3f' % ans)


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

Submission status: Accepted

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

from math import sqrt
from heapq import heappush, heappop
from collections import defaultdict


class UnionFind(object):
    def __init__(self, n):
        self.n = n
        self.par = [-1] * n
    
    def find(self, x):
        if self.par[x] < 0:
            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 False
        else:
            if self.par[x] > self.par[y]:
                x, y = y, x
            self.par[x] += self.par[y]
            self.par[y] = x
            return True

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

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

    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.par) if x < 0]

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


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

    X, Y, Z, R = [], [], [], []
    for _ in range(N):
        xi, yi, zi, ri = map(float, input().split())
        X.append(xi)
        Y.append(yi)
        Z.append(zi)
        R.append(ri)

    # グラフ構造を作成？
    # 短いやつをつなげていって，森じゃなくなったらOKかな？
    uf = UnionFind(N)
    cost = 0.0
    edges = []
    for i in range(N):
        for j in range(i + 1, N):
            dx = X[i] - X[j]
            dy = Y[i] - Y[j]
            dz = Z[i] - Z[j]
            dij = sqrt(dx * dx + dy * dy + dz * dz) - R[i] - R[j]
            heappush(edges, (dij, i, j))

    # Kruskal
    while len(edges) > 0:
        (w, u, v) = heappop(edges)
        if uf.unite(u, v):
            if w > 0:
                cost += w
    print("{:.3f}".format(cost))

Submission status: Accepted

Solution code:
from decimal import *

class UnionFind():
    # 初めは全ての頂点が別々の木の根
    def __init__(self, n):  # n要素で初期化
        self.parent = list(range(n)) # 親
        self.rank = [0] * n   # 木の深さ
        self._nsets = n  # 集合の数

    def root_of(self, x):
        children = [x]
        while self.parent[x] != x:
            x = self.parent[x]
            children.append(x)

        for ch in children:
            self.parent[ch] = x
        return x

    # xとyの属する集合を併合
    def union(self, x, y):
        rx = self.root_of(x)
        ry = self.root_of(y)
        if rx == ry:
            return
        if self.rank[rx] < self.rank[ry]: # ランクの小さい木から大きい木の根に辺を張る
            self.parent[rx] = ry  # rxをryの子とする
        else:
            self.parent[ry] = rx
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1
        self._nsets -= 1

    # 同じ集合に属するかどうか
    def same(self, x, y):
        return self.root_of(x) == self.root_of(y)

    # 集合の数
    def get_nsets(self):
        return self._nsets

while True:
    N = int(input())
    if N == 0: break
    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] = [Decimal(a) for a in input().split()]

    E = []
    uf = UnionFind(N)
    for i in range(N):
        for j in range(i + 1, N):
            dsq = pow(x[i] - x[j], 2) + pow(y[i] - y[j], 2) + pow(z[i] - z[j], 2)
            rsq = pow(r[i] + r[j], 2)
            if dsq <= rsq:
                uf.union(i, j)
            else:
                E.append((dsq.sqrt() - r[i] - r[j], (i, j)))

    E.sort()
    ans = Decimal('0')
    for d, (i, j) in E:
        if uf.get_nsets() == 1:  break
        if uf.same(i, j): continue
        uf.union(i, j)
        ans += d

    ans = ans.quantize(Decimal('0.001'), rounding = ROUND_HALF_UP)
    print(ans)

Submission status: Accepted

Solution code:
# https://onlinejudge.u-aizu.ac.jp/problems/1127


class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [i for i in range(n)]

    def root(self, x):
        if self.parents[x] == x:
            return x
        else:
            self.parents[x] = self.root(self.parents[x])
            return self.parents[x]

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

        if x == y:
            return False

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

        self.parents[y] = x
        return True

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


def distance(x1, y1, z1, x2, y2, z2):
    dxx = (x1 - x2) ** 2
    dyy = (y1 - y2) ** 2
    dzz = (z1 - z2) ** 2
    return (dxx + dyy + dzz) ** (1/2)


def solve(n, rows):
    # (start, end, corridors_length)
    edges = []
    for i in range(len(rows)):
        for j in range(i + 1, len(rows)):
            x1, y1, z1, r1 = rows[i]
            x2, y2, z2, r2 = rows[j]
            d = distance(x1, y1, z1, x2, y2, z2)
            # print(i, j, d)
            if d > r1 + r2:
                edges.append((i, j, d-r1-r2))
            else:
                edges.append((i, j, 0))

    edges.sort(key=lambda x: x[2])
    # print(edges)

    result = 0
    uf = UnionFind(n)
    for edge in edges:
        s, t, d = edge
        unioned = uf.union(s, t)
        if unioned:
            result += d

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


if __name__ == "__main__":
    while(True):
        n = int(input())
        if n == 0:
            break
        rows = [list(map(float, input().split())) for _ in range(n)]
        solve(n, rows)

Submission status: Accepted

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))
lis = lambda x : int(x.replace('.',''))
li2 = lambda : list(map(lis,input().split()))

# かぶっているか判定
# 最短判定

import math

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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if(x == y):
            return False
        if(self.d[x] > self.d[y]):
            x, y = y, x
        self.d[x] += self.d[y]
        self.d[y] = x
        return True

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

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

def judgeContact(a,b):
    # k = (a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2 - (a[3] + b[3]) ** 2
    k = math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2 + (a[2]-b[2])**2) - (a[3] + b[3]) 
    if k <= 0:
        return -1
    else:
        return k

def calc(n):
    ps = []
    uf = UnionFind(n)
    d = []
    cnt = 0
    ans = 0

    for i in range(n):
        p = li2()
        
        # かぶり判定
        for k,j in enumerate(ps):
            v = judgeContact(p,j) 
            if v == -1:
                # d.append([0,i,k])
                if uf.same(i,k) == False:
                    uf.union(i,k)
                    cnt += 1
            else:
                d.append([v,i,k])
        ps.append(p)

    d.sort()
    for i in d:
        if cnt == n-1:
            break

        if uf.same(i[1],i[2]):
            continue
        
        uf.union(i[1],i[2])
        # print('union',i[1],i[2],cnt,i[0])
        cnt += 1
        ans += i[0]

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


while 1:
    n = ii()
    if n == 0:
        break
    
    calc(n)

Submission status: Accepted

Solution code:
import queue
import math


def root(node):
    if nodes[node] == node:
        return node
    nodes[node] = root(nodes[node])
    return nodes[node]


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

    cells = [list(map(float, input().split())) for _ in range(n)]

    nodes = [i for i in range(n)]

    q = queue.PriorityQueue()
    cost = 0
    count = n
    for i in range(n - 1):
        for j in range(i, n):
            d = math.sqrt((cells[i][0] - cells[j][0])**2 + (cells[i][1] - cells[j][1])**2 + (cells[i][2] - cells[j][2])**2)
            if d <= cells[i][3] + cells[j][3]:
                if root(i) != root(j):
                    nodes[root(i)] = root(j)
                    count += 1
            else:
                q.put((d - cells[i][3] - cells[j][3], i, j))
    while not q.empty():
        if count <= 1:
            break
        d, i, j = q.get()
        if root(i) != root(j):
            nodes[root(i)] = root(j)
            count -= 1
            cost += d
    print('{:.3f}'.format(cost))

Submission status: Accepted

Solution code:
from math import sqrt

class UF():
  def __init__(self, N):
    self.parents = [-1] * (N+1)

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

  def union(self, u,v):
    p1,p2 = self.find(u),self.find(v)
    if p1 == p2: return

    if p1 > p2:
      p1,p2 = p2,p1
    self.parents[p1] += self.parents[p2]
    self.parents[p2] = p1

  def same(self, u, v):
    return self.find(u) == self.find(v)

ans = []
while True:
  # sphere-shaped
  n = int(input())
  if n==0: exit()
  C = []
  # for _ in range(n):
    # C.append(list(map(float,input().split())))
  C = [[float(i) for i in input().split()] for _ in range(n)]

  uf = UF(n)
  edges = []
  for i in range(n):
    for j in range(i+1, n):
      x1,y1,z1,r1 = C[i]
      x2,y2,z2,r2 = C[j]
      d = ((x1-x2)**2+(y1-y2)**2+(z1-z2)**2)**0.5-r1-r2
      if d <= 0:
        uf.union(i,j)
      else:
        edges.append((d,i,j))
  edges.sort(key=lambda x: x[0])

  res = 0
  for d,u,v in edges:
    if not uf.same(u,v):
      uf.union(u,v)
      res += d

  print(f"{res:.3f}")

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
 
sys.setrecursionlimit(10 ** 7)
 
from collections import defaultdict
 
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())
# list(map(int, input().split()))
class UnionFind(object):
    def __init__(self, n = 1):
        self.link = [i for i in range(n)]
        self.size = [1 for _ in range(n)]

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

        # re-connect union find to make the height of tree lower
        # you can use while, but recursion makes it easier to reconnect
        self.link[x] = self.find(self.link[x])
        return self.link[x]

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

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

        if self.size[x] < self.size[y]:
            x, y = y, x
        self.link[y] = x
        self.size[x] += self.size[y]
    
    def get_size(self, x):
        x = self.find(x)
        return self.size[x]


while True:
    N = int(input())
    if N == 0:
        break
    cells = [0] * N
    for i in range(N):
        x, y, z, r = map(float, input().split())
        cells[i] = (x, y, z, r)
    
    edges = []
    for i in range(N):
        for j in range(i + 1, N):
            x1, y1, z1, r1 = cells[i]
            x2, y2, z2, r2 = cells[j]
            d = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2)
            if d <= r1 + r2:
                d = 0
            else:
                d = d - r1 - r2
            edges.append((d, i, j))

    edges = sorted(edges)

    u = UnionFind(N)
    ans = 0
    for e in edges:
        d, a, b = e
        if u.is_same(a, b):
            continue
        u.unite(a, b)
        ans += d
    print('{:.3f}'.format(ans))

Submission status: Accepted

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

    # 検索
    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)
      
      

T = True
while T:
  n = int(input())
  if n == 0:
    quit()
    
  data = UnionFind(n + 1)
  x = [0] * n
  for i in range(n):
    x[i] = list(map(float, input().split()))
  p = int(n * (n - 1) / 2)
  kumi = [0] * p
  q = 0
  for i in range(n):
    one = x[i]
    for j in range(i + 1, n):
      two = x[j]
      L1 = (one[0] - two[0]) ** 2 + (one[1] - two[1]) ** 2 + (one[2] - two[2]) ** 2
      L2 = L1 ** (1 / 2) - (one[3] + two[3])
      L2 = max(L2, 0)
      kumi[q] = [i, j, L2]
      q += 1
  kumi = sorted(kumi, key = lambda x:x[2])
  ans = 0
  for i in range(p):
    x, y, z = kumi[i][0], kumi[i][1], kumi[i][2]
    if not data.same_check(x, y):
      data.union(x, y)
      ans += z
  print('{:.3f}'.format(ans))