Problem:


Closest Pair

For given n points in metric space, find the distance of the closest points.

Input

n
x0 y0
x1 y1
:
xn-1 yn-1

The first integer n is the number of points.

In the following n lines, the coordinate of the i-th point is given by two real numbers xi and yi. Each value is a real number with at most 6 digits after the decimal point.

Output

Print the distance in a line. The output values should be in a decimal fraction with an error less than 0.000001.

Constraints

2 ≤ n ≤ 100,000

-100 ≤ x, y ≤ 100

Sample Input 1

2
0.0 0.0
1.0 0.0

Sample Output 1

1.000000

Sample Input 2

3
0.0 0.0
2.0 0.0
1.0 1.0

Sample Output 2

1.41421356237



Sample input:
2
0.0 0.0
1.0 0.0


Sample output:
1.000000

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter
from itertools import permutations
from math import sqrt

def solve(a: list, axis: int = 0):
    length = len(a)
    if length <= 3:
        return min(sqrt((p1[axis]-p2[axis])**2+(p1[not axis]-p2[not axis])**2) for p1, p2 in permutations(a, 2))

    med = length//2
    left, right = a[:med], a[med:]
    delta = min(solve(left, axis), solve(right, axis))
    median_x = a[med][axis]
    m_a = []
        
    for p in left[::-1]:
        if p[axis] < median_x-delta:
            break
        m_a.append(p)
    for p in right:
        if p[axis] > median_x+delta:
            break
        m_a.append(p)
    m_a.sort(key=itemgetter(not axis))

    for i, p1 in enumerate(m_a):
        ub = p1[not axis] + delta
        for j, p2 in enumerate(m_a[i+1:]):
            if p2[not axis] > ub:
                break
            delta = min(delta, sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2))

    return delta

if __name__ == "__main__":
    N = int(input())
    a = sorted([tuple(map(float, l.split())) for l in sys.stdin.readlines()])
    axis = 0 if len(set(p[0] for p in a)) > len(set(p[1] for p in a)) else 1
    print("{:.10f}".format(solve(a, axis)))

Submission status: Accepted

Solution code:
from sys import stdin
from operator import attrgetter
readline = stdin.readline


def norm(a):
    return a.real * a.real + a.imag * a.imag


def closest_pair(p):
    if len(p) <= 1:
        return float('inf')
    m = len(p) // 2
    d = min(closest_pair(p[:m]), closest_pair(p[m:]))
    p = [pi for pi in p if p[m].imag - d < pi.imag < p[m].imag + d]
    return brute_force(p, d)

def brute_force(p, d=float('inf')):
    p.sort(key=attrgetter('real'))
    for i in range(1, len(p)):
        for j in reversed(range(i)):
            tmp = p[i] - p[j]
            if d < tmp.real:
                break
            tmp = abs(tmp)
            if d > tmp:
                d = tmp
    return d


def main():
    n = int(readline())
    p = [map(float, readline().split()) for _ in range(n)]
    p = [x + y * 1j for x, y in p]

    p.sort(key=attrgetter('imag'))
    print('{:.6f}'.format(closest_pair(p)))
main()

Submission status: Accepted

Solution code:
from math import sqrt
n = input()
ps = [map(float, raw_input().split()) for i in xrange(n)]
ps.sort()
INF = 10**9

def cp_rec(ps, i, n):
    if n <= 1:
        return INF, [ps[i]]
    m = n/2
    x = ps[i+m][0]
    d1, qs1 = cp_rec(ps, i, m)
    d2, qs2 = cp_rec(ps, i+m, n-m)
    d = min(d1, d2)
    # merge
    qs = [None]*n
    s = t = idx = 0
    while s < m and t < n-m:
        if qs1[s][1] < qs2[t][1]:
            qs[idx] = qs1[s]; s += 1
        else:
            qs[idx] = qs2[t]; t += 1
        idx += 1
    while s < m:
        qs[idx] = qs1[s]; s += 1
        idx += 1
    while t < n-m:
        qs[idx] = qs2[t]; t += 1
        idx += 1
    b = []
    for i in xrange(n):
        ax, ay = q = qs[i]
        if abs(ax - x) >= d:
            continue
        for j in xrange(len(b)-1, -1, -1):
            dx = ax - b[j][0]
            dy = ay - b[j][1]
            if dy >= d: break
            d = min(d, sqrt(dx**2 + dy**2))
        b.append(q)
    return d, qs
def closest_pair(ps):
    n = len(ps)
    return cp_rec(ps, 0, n)[0]
print "%.09f" % closest_pair(ps)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
3
0.0 0.0
2.0 0.0
1.0 1.0

output:
1.41421356237
"""

import math
import sys
from operator import attrgetter


class ClosestPair(object):
    def __init__(self, ):
        """
        Init closest pairs points set.
        """
        _input = sys.stdin.readlines()
        p_num = int(_input[0])
        points = map(lambda x: x.split(), _input[1:])
        p_list = [complex(float(x), float(y)) for x, y in points]
        p_list.sort(key=attrgetter('real'))
        # assert len(p_list) == p_num
        # print(p_list)
        ans = self.closest_pair(array=p_list, array_length=p_num)
        print(('{:.6f}'.format(ans)))

    def closest_pair(self, array, array_length):
        if array_length <= 1:
            return float('inf')
        mid = array_length // 2
        mid_real = array[mid].real
        d = min(self.closest_pair(array[:mid], mid).real,
                self.closest_pair(array[mid:], array_length - mid).real)

        return self.brute_force(array, mid_real, d)

    @staticmethod
    def brute_force(array, mid_real, d=float('inf')):
        array.sort(key=attrgetter('imag'))
        min_stack = list()
        for ele in array:
            size = len(min_stack)
            if abs(ele.real - mid_real) >= d:
                continue

            for j in range(size):
                dx = ele.real - min_stack[size - j - 1].real
                dy = ele.imag - min_stack[size - j - 1].imag
                if dy >= d:
                    break
                d = min(d, math.sqrt(dx ** 2 + dy ** 2))

            min_stack.append(ele)

        return d


if __name__ == '__main__':
    case = ClosestPair()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
3
0.0 0.0
2.0 0.0
1.0 1.0

output:
1.41421356237
"""

import sys
from operator import attrgetter


class ClosestPair(object):
    def __init__(self, ):
        """
        Init closest pairs points set.
        """
        _input = sys.stdin.readlines()
        p_num = int(_input[0])
        points = map(lambda x: x.split(), _input[1:])
        p_list = [complex(float(x), float(y)) for x, y in points]
        # pre_sort by axis_X
        p_list.sort(key=attrgetter('real'))

        ans = self.closest_pair(array=p_list, array_length=p_num)
        print(('{:.6f}'.format(ans)))

    def closest_pair(self, array, array_length):
        if array_length <= 1:
            return float('inf')
        mid = array_length // 2
        mid_real = array[mid].real
        d = min(self.closest_pair(array[:mid], mid),
                self.closest_pair(array[mid:], array_length - mid))

        # sort by axis_Y while recursively solve d
        array.sort(key=attrgetter('imag'))

        min_stack = list()
        for ele in array:
            size = len(min_stack)

            if abs(ele.real - mid_real) >= d:
                continue

            for j in range(size):
                alt = ele - min_stack[size - j - 1]
                if alt.imag >= d:
                    break
                d = min(d, abs(alt))

            min_stack.append(ele)

        return d


if __name__ == '__main__':
    case = ClosestPair()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
3
0.0 0.0
2.0 0.0
1.0 1.0

output:
1.41421356237
"""

import sys
from operator import attrgetter


class ClosestPair(object):
    def __init__(self, ):
        """
        Init closest pairs points set.
        """
        _input = sys.stdin.readlines()
        p_num = int(_input[0])
        points = map(lambda x: x.split(), _input[1:])
        p_list = [complex(float(x), float(y)) for x, y in points]
        # pre_sort by axis_X
        p_list.sort(key=attrgetter('real'))

        ans = self.closest_pair(array=p_list, array_length=p_num)
        print(('{:.6f}'.format(ans)))

    def closest_pair(self, array, array_length):
        if array_length <= 1:
            return float('inf')
        mid_idx = array_length // 2
        div_line = array[mid_idx].real
        d_min = min(self.closest_pair(array[:mid_idx], mid_idx),
                self.closest_pair(array[mid_idx:], array_length - mid_idx))

        # sort array_part by axis_Y while recursively comparing
        array.sort(key=attrgetter('imag'))

        min_stack = list()
        for ele in array:
            size = len(min_stack)

            if abs(ele.real - div_line) >= d_min:
                continue

            for j in range(size):
                alt = ele - min_stack[size - j - 1]
                if alt.imag >= d_min:
                    break
                d_min = min(d_min, abs(alt))

            min_stack.append(ele)

        return d_min


if __name__ == '__main__':
    case = ClosestPair()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
input:
3
0.0 0.0
2.0 0.0
1.0 1.0

output:
1.41421356237
"""

import sys
from operator import attrgetter


class ClosestPair(object):
    def __init__(self, in_data):
        """
        Init closest pairs points set.
        """
        self.p_num = int(in_data[0])
        points = map(lambda x: x.split(), in_data[1:])
        p_list = [complex(float(x), float(y)) for x, y in points]
        # pre_sort by axis_X
        self.p_list = sorted(p_list, key=attrgetter('real'))

    def closest_pair(self, array, array_length):
        if array_length <= 1:
            return float('inf')
        mid_idx = array_length // 2
        div_line = array[mid_idx].real
        d_min = min(self.closest_pair(array[:mid_idx], mid_idx),
                    self.closest_pair(array[mid_idx:], array_length - mid_idx))

        # sort array_part by axis_Y while recursively comparing
        array.sort(key=attrgetter('imag'))

        min_stack = list()
        for ele in array:
            size = len(min_stack)

            # eliminate p which distance(p,div_line) >= d
            if abs(ele.real - div_line) >= d_min:
                continue

            for j in range(size):
                alt = ele - min_stack[size - j - 1]
                if alt.imag >= d_min:
                    break
                d_min = min(d_min, abs(alt))

            min_stack.append(ele)

        return d_min

    def solve(self):
        return self.closest_pair(array=self.p_list, array_length=self.p_num)


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    case = ClosestPair(in_data=_input)
    print('{:.6f}'.format(case.solve()))

Submission status: Accepted

Solution code:
import itertools

def _get_distance(p1, p2):
    return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5

def _get_min_distance(points):
    min_d = 400
    for p1, p2 in itertools.combinations(points, 2):
        min_d = min(min_d, _get_distance(p1, p2))
    return min_d

def closest_pair_distance(points, axis):
    # axis: x; 0, y; 1
    n = len(points)
    if n <= 3:
        return _get_min_distance(points)
    else:
        mid = n // 2
        px, py = zip(*points)
        if len(set(px)) > len(set(py)):
            if axis:
                points.sort(key = lambda p: p[0])
            axis1 = 0
            axis2 = 1
        else:
            if not axis:
                points.sort(key = lambda p: p[1])
            axis1 = 1
            axis2 = 0
        A_points = points[:mid]
        B_points = points[mid:]
        d_Amin = closest_pair_distance(A_points.copy(), axis1)
        d_Bmin = closest_pair_distance(B_points.copy(), axis1)
        dist = min(d_Amin, d_Bmin)
        min_d = dist
        for ap in A_points[::-1]:
            if B_points[0][axis1] - ap[axis1] >= dist:
                break
            for bp in B_points:
                if bp[axis1] - ap[axis1] >= dist:
                    break
                if ap[axis2] - dist < bp[axis2] < ap[axis2] + dist:
                    min_d = min(min_d, _get_distance(ap, bp))
        return min_d

# Acceptance of input
import sys

file_input = sys.stdin

n = int(file_input.readline())

P = [tuple(map(float, line.split())) for line in file_input]

# Solve
P.sort(key = lambda p: p[0])
ans = closest_pair_distance(P, 0)

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

Submission status: Accepted

Solution code:
import itertools

def _get_distance(p1, p2):
    return ((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2) ** 0.5

def _get_min_distance(points):
    min_d = 400
    for p1, p2 in itertools.combinations(points, 2):
        min_d = min(min_d, _get_distance(p1, p2))
    return min_d

def closest_pair_distance(points):
    n = len(points)
    if n <= 3:
        return _get_min_distance(points)
    else:
        mid = n // 2
        px, py = zip(*points)
        if len(set(px)) > len(set(py)):
            points.sort(key = lambda p: p[0])
            # axis: x; 0, y; 1
            axis1 = 0
            axis2 = 1
        else:
            points.sort(key = lambda p: p[1])
            axis1 = 1
            axis2 = 0
        A_points = points[:mid]
        B_points = points[mid:]
        d_Amin = closest_pair_distance(A_points.copy())
        d_Bmin = closest_pair_distance(B_points.copy())
        dist = min(d_Amin, d_Bmin)
        min_d = dist
        for ap in A_points[::-1]:
            if B_points[0][axis1] - ap[axis1] >= dist:
                break
            for bp in B_points:
                if bp[axis1] - ap[axis1] >= dist:
                    break
                if ap[axis2] - dist < bp[axis2] < ap[axis2] + dist:
                    min_d = min(min_d, _get_distance(ap, bp))
        return min_d

# Acceptance of input
import sys

file_input = sys.stdin

n = int(file_input.readline())

P = [tuple(map(float, line.split())) for line in file_input]

# Solve
ans = closest_pair_distance(P)

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

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter
from itertools import permutations
from math import sqrt

def solve(a: list):
    length = len(a)
    if length <= 3:
        return min(sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) for p1, p2 in permutations(a, 2))

    x_set_len = len(set(x for (x, _) in a))
    axis = 0 if x_set_len > length/2 else 1
    a.sort(key=itemgetter(axis))
    mid_index = length//2
    left, right = a[:mid_index], a[mid_index:]
    delta = min(solve(left), solve(right))
    median = a[mid_index][axis]
    m_a = []
        
    for p in left[::-1]:
        if p[axis] < median-delta:
            break
        m_a.append(p)
    for p in right:
        if p[axis] > median+delta:
            break
        m_a.append(p)
    m_a.sort(key=itemgetter(not axis))

    for i, p1 in enumerate(m_a):
        ub = p1[not axis] + delta
        for j, p2 in enumerate(m_a[i+1:]):
            if p2[not axis] > ub:
                break
            delta = min(delta, sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2))

    return delta

if __name__ == "__main__":
    N = int(input())
    a = [tuple(map(float, l.split())) for l in sys.stdin.readlines()]
    print("{:.10f}".format(solve(a)))

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter
from itertools import permutations
from math import sqrt

def solve(a: list):
    length = len(a)
    if length <= 3:
        return min(sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) for p1, p2 in permutations(a, 2))

    x_set_len = len(set(x for (x, _) in a))
    axis = 0 if x_set_len > length/2 else 1
    a.sort(key=itemgetter(axis))
    mid_index = length//2
    left, right = a[:mid_index], a[mid_index:]
    delta = min(solve(left), solve(right))
    median = a[mid_index][axis]
    m_a = []
    append = m_a.append
        
    for p in left[::-1]:
        if p[axis] < median-delta:
            break
        append(p)
    for p in right:
        if p[axis] > median+delta:
            break
        append(p)
    m_a.sort(key=itemgetter(not axis))

    for i, p1 in enumerate(m_a):
        ub = p1[not axis] + delta
        for j, p2 in enumerate(m_a[i+1:]):
            if p2[not axis] > ub:
                break
            dist = sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)
            if dist < delta:
                delta = dist

    return delta

if __name__ == "__main__":
    N = int(input())
    a = [tuple(map(float, l.split())) for l in sys.stdin.readlines()]
    print("{:.10f}".format(solve(a)))

Submission status: Accepted

Solution code:
import sys
from operator import itemgetter
from itertools import combinations, takewhile
from math import sqrt

def solve(a: list, sorted_axis: int = -1):
    length = len(a)
    if length <= 3:
        return sqrt(min((x1-x2)**2+(y1-y2)**2 for (x1, y1), (x2, y2) in combinations(a, 2)))

    x_set_len = len(set(x for x, _ in a))
    axis1 = 0 if x_set_len > length/2 else 1

    if sorted_axis != axis1:
        a.sort(key=itemgetter(axis1))

    mid_index = length//2
    left, right = a[:mid_index], a[mid_index:]
    delta = min(solve(left, axis1), solve(right, axis1))

    axis2 = not axis1
    median = a[mid_index][axis1]
    mid_a = sorted([p for _iter in (
        (takewhile(lambda p: median-delta < p[axis1], left[::-1])),
        (takewhile(lambda p: p[axis1] < median+delta, right))
    ) for p in _iter], key=itemgetter(axis2))

    for i, (x1, y1) in enumerate(mid_a):
        ub = (x1 if axis1 else y1) + delta
        for x2, y2 in takewhile(lambda p: p[axis2] < ub, mid_a[i+1:]):
            delta = min(delta, sqrt((x1-x2)**2+(y1-y2)**2))

    return delta

if __name__ == "__main__":
    N = int(input())
    a = [tuple(map(float, l.split())) for l in sys.stdin.readlines()]
    print("{:.10f}".format(solve(a)))

Submission status: Accepted

Solution code:
# 最近点対を分割統治法で求める
from math import sqrt
n = int(input())
ps = [list(map(float, input().strip().split())) for i in range(n)]
# print(ps)
# Q: なぜ、最初にx座標についてソートされている必要があるのか？
# A: 二つの区間が統合されるとき、dには2つの区間における最小２点間距離が入っており、
#    統合された区間における最小値は、それ以下を探索するようになっている。
#    この時、各区間A:[i, i+m), B:[i+m, n)での最小値は、
#    [Aの任意の点]と[Bの任意の点]の距離は、境界(i+m-1とi+m)を除いてこの最小値以上であるという前提が成り立つ。
#    そのため、統合された区間において探索するのはabs(dx - x) <= dのみを探索すれば良い。
#    仮にxでソートされていない場合、上の前提が成り立たないため、統合しても結局全ての点で
#    距離を計算しなくてはいけない。
ps.sort()
# print(ps)
INF = 10**9

# cp_rec - 再帰用関数
# 入力: 配列と区間
# 出力: 距離と区間内の要素をY座標でソートした配列
def cp_rec(ps, i, n):
    if n <= 1:
        return INF, [ps[i]]
    m = int(n/2)
    x = ps[i+m][0] # 半分に分割した境界のX座標
    # 配列を半分に分割して計算
    d1, qs1 = cp_rec(ps, i, m)
    d2, qs2 = cp_rec(ps, i+m, n-m)
    d = min(d1, d2)
    # Y座標が小さい順にmergeする
    qs = [None]*n
    s = t = idx = 0
    while s < m and t < n-m:
        if qs1[s][1] < qs2[t][1]:
            qs[idx] = qs1[s]; s += 1
        else:
            qs[idx] = qs2[t]; t += 1
        idx += 1
    while s < m:
        qs[idx] = qs1[s]; s += 1
        idx += 1
    while t < n-m:
        qs[idx] = qs2[t]; t += 1
        idx += 1
    # 境界のX座標x(=ps[i+m][0])から距離がd以下のものについて距離を計算していく
    # bは境界のX座標から距離d以下のものを集めたものが、Y座標の昇順に入っている。
    b = []
    for i in range(n):
        ax, ay = q = qs[i]
        if abs(ax - x) >= d:
            continue
        # Y座標について、qs[i]から距離がd以下のj(<i)について計算していく
        for j in range(len(b)-1, -1, -1):
            dx = ax - b[j][0]
            dy = ay - b[j][1]
            # このループは, ayとb[j][1]が近い順に取り出していいるため、
            # 一度 dy >= 0となれば、あとは探索する必要はない。
            if dy >= d: break
            d = min(d, sqrt(dx**2 + dy**2))
        b.append(q)
    # dは、区間[i, i+n)における最小区間距離を指している。
    # qsは[i, i+n)でY座標についてソートされている。
    return d, qs

# ps: ソートした二次元座標のlist
def closest_pair(ps):
    n = len(ps)
    return cp_rec(ps, 0, n)[0]

print("{:.09f}".format(closest_pair(ps)))

Submission status: Accepted

Solution code:
INF = 10**16

# ソートしてから入れる
def ClosestDFS(Points):
    l = len(Points)
    if l <= 1: return INF, Points
    d1, nearPoints1 = ClosestDFS(Points[:l//2])
    d2, nearPoints2 = ClosestDFS(Points[l//2:])
    retPoints = []
    ind = 0
    for p1x, p1y in nearPoints1:
        while ind != len(nearPoints2) and nearPoints2[ind][1] < p1y:
            retPoints.append(nearPoints2[ind])
            ind += 1
        retPoints.append((p1x, p1y))
    while ind != len(nearPoints2):
        retPoints.append(nearPoints2[ind])
        ind += 1
    
    d = min(d1, d2)
    B = []
    border_x = Points[l//2][0]
    for px, py in retPoints:
        if abs(border_x-px) > d: continue
        for bx, by in reversed(B):
            if py - by > d: break
            d = min(d, ((px-bx)**2+(py-by)**2)**0.5)
        B.append((px, py))
    return d, retPoints

def ClosestPair(Points):
    Points.sort()
    d, _ = ClosestDFS(Points)
    return d

import sys
input = sys.stdin.readline

def main():
    N = int(input())
    Points = [list(map(float, input().split())) for _ in range(N)]
    print("{:.8f}".format(ClosestPair(Points)))

if __name__ == "__main__":
    main()