Problem:
Closest Pair For given n points in metric space, find the distance of the closest points. Input  n  x 0  y 0  x 1  y 1 : x n-1  y n-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 x i and y i . 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

Solution (Python):
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()

Solution (Python):
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)
    
    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)

Solution (Python):



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

Solution (Python):



"""
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]
        
        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))

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

Solution (Python):



"""
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]
        
        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))

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

Solution (Python):



"""
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]
        
        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))

        
        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

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

Solution (Python):
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):
    
    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


import sys

file_input = sys.stdin

n = int(file_input.readline())

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


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

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

Solution (Python):
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])
            
            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


import sys

file_input = sys.stdin

n = int(file_input.readline())

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


ans = closest_pair_distance(P)

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

Solution (Python):
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)))

Solution (Python):
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)))

Solution (Python):
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)))

Solution (Python):

from math import sqrt
n = int(input())
ps = [list(map(float, input().strip().split())) for i in range(n)]









ps.sort()

INF = 10**9




def cp_rec(ps, i, n):
    if n <= 1:
        return INF, [ps[i]]
    m = int(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)
    
    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 range(n):
        ax, ay = q = qs[i]
        if abs(ax - x) >= d:
            continue
        
        for j in range(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}".format(closest_pair(ps)))

Solution (Python):
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()