Problem:


Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8



Sample input:
3
1 5
3 9
7 8


Sample output:
3

Submission status: Wrong Answer

Solution code:
n=int(input())
s=[]
for i in range(n):
    a,b=map(int,input().split())
    s.append([a,b,i])
x=sorted(s)
y=sorted(s,key=lambda x:x[1])
print(x,y)
t=[]
for i in range(1,n):
    t.append([x[i-1][2],x[i][2],x[i][0]-x[i-1][0]])
    t.append([y[i-1][2],y[i][2],y[i][1]-y[i-1][1]])
t=sorted(t,key=lambda x:x[2])
d=[i for i in range(n+1)]
p=[1]*(n+1)
def f(x):
    if x==d[x]:
        return x
    x=d[x]
    return f(d[x])
r=0
for a,b,c in t:
    a=f(a)
    b=f(b)
    if a!=b:
        if p[a]>p[b]:
            d[b]=a
            p[a]+=p[b]
            r+=c
        else:
            d[a]=b
            p[b]+=p[a]
            r+=c
print(r)

Submission status: Wrong Answer

Solution code:



class uf_tree():

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

    def indep(self):
        dep =0
        for i in range(self.n):
            if i == self.par[i]:
                dep += 1

        return dep

    def unite(self,child,mas):
        if self.root(child) == self.root(mas):
            return
        else:
            self.par[self.root(child)] = self.root(mas)

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

    def same(self,x,y):
        if self.root(x) == self.root(y):
            return True
        else:
            return False
def kruscal(n,edge_arr):
    edge_arr.sort(key=lambda x:x[2])
    ans = []
    tree = uf_tree(n)
    for e in edge_arr:
        s = e[0]-1
        g = e[1]-1
        if tree.same(s,g):
            continue
        else:
            ans.append(e)
            tree.unite(s,g)
    return ans

def main():
    n = int(input())
    p = [[0,0,0] for i in range(n)]
    edge = []
    for i in range(n):
        x,y = map(int,input().split())
        p[i][0] = x
        p[i][1] = y
        p[i][2] = i+1

    p.sort(key = lambda x:x[0])
    for i in range(n-1):
        cost = min(abs(p[i+1][0]-p[i][0]),abs(p[i+1][1]-p[i][1]))
        edge.append([p[i][2],p[i+1][2],cost])

    p.sort(key = lambda x:x[1])
    for i in range(n-1):
        cost = min(abs(p[i+1][0]-p[i][0]),abs(p[i+1][1]-p[i][1]))
        edge.append([p[i][2],p[i+1][2],cost])

    ans = kruscal(n,edge)
    tot = 0
    for e in ans:
        tot += e[2]
    print(tot)

Submission status: Wrong Answer

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

def ri():
    return int(input())

def rl():
    return list(input().split())

def rli():
    return list(map(int, input().split()))

def main():
    n = ri()
    lp = []
    for i in range(n):
        x, y = rli()
        lp.append((i, x, y))
    lp.sort(key=lambda e: e[1])
    connects = []
    for i in range(n-1):
        cost = lp[i+1][1]-lp[i][1]
        connects.append((cost, lp[i][0], lp[i+1][0]))
    lp.sort(key=lambda e: e[2])
    for i in range(n-1):
        cost = lp[i+1][2]-lp[i][2]
        connects.append((cost, lp[i][0], lp[i+1][0]))
    connects.sort()
    used = set()
    ans = 0
    for c in connects:
        if c[1] in used and c[2] in used:
            continue
        used.add(c[1])
        used.add(c[2])
        ans += c[0]
        if len(used) == n:
            break
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from heapq import *

def prim(V, E):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
    Output:
        the edges of the minimum weight tree and its weight
    '''
    N = len(V)
    weight = 0; edges = [];
    used = [False]*N; used[0] = True; n_used = 1;
    heap = [(c, 0, v) for v, c in E[0].items()]; heapify(heap)
    while heap and n_used < N:
        c, u, v = heappop(heap)
        if used[v]: continue
        used[v] = True; n_used += 1; edges.append((u, v))
        weight += c
        for w, d in E[v].items():
            if not used[w]: heappush(heap, (d, v, w))
    return edges, weight

N = int(input())
cities = [(a, b, i) for i, (a, b) in enumerate([tuple(map(int, input().split())) for _ in range(N)])]
sorted_x, sorted_y = sorted(cities, key=lambda x:x[0]), sorted(cities, key=lambda x:x[1])
E = {i: {} for i in range(N)}
for i in range(N-1):
    (a1, _, u), (a2, _, v) = sorted_x[i], sorted_x[i+1]
    E[u][v] = a2 - a1
    E[v][u] = E[u][v]
    (_, b1, u), (_, b2, v) = sorted_y[i], sorted_y[i+1]
    E[u][v] = min(b2 - b1, E[u][v]) if E[u].get(v) is not None else b2 - b1
    E[v][u] = E[u][v]
V = list(range(N))
_, ans = prim(V, E)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from heapq import *

def prim(V, E):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
    Output:
        the edges of the minimum weight tree and its weight
    '''
    N = len(V)
    weight = 0; edges = [];
    used = [False]*N; used[0] = True; n_used = 1;
    heap = [(c, 0, v) for v, c in E[0].items()]; heapify(heap)
    while heap and n_used < N:
        c, u, v = heappop(heap)
        if used[v]: continue
        used[v] = True; n_used += 1; edges.append((u, v))
        weight += c
        for w, d in E[v].items():
            if not used[w]: heappush(heap, (d, v, w))
    return edges, weight

N = int(input())
cities = [(a, b, i) for i, (a, b) in enumerate([tuple(map(int, input().split())) for _ in range(N)])]
sorted_x, sorted_y = sorted(cities, key=lambda x:x[0]), sorted(cities, key=lambda x:x[1])
E = {i: defaultdict(int) for i in range(N)}
for i in range(N-1):
    (a1, _, u), (a2, _, v) = sorted_x[i], sorted_x[i+1]
    E[u][v] = a2 - a1
    E[v][u] = E[u][v]
    (_, b1, u), (_, b2, v) = sorted_y[i], sorted_y[i+1]
    E[u][v] = min(b2 - b1, E[u][v]) if E[u][v] > 0 else b2 - b1
    E[v][u] = E[u][v]
V = list(range(N))
_, ans = prim(V, E)
print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from heapq import *

def prim(V, E):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
    Output:
        the edges of the minimum weight tree and its weight
    '''
    N = len(V)
    weight = 0; edges = [];
    used = [False]*N; used[0] = True; n_used = 1;
    heap = [(c, 0, v) for v, c in E[0].items()]; heapify(heap)
    while heap and n_used < N:
        c, u, v = heappop(heap)
        if used[v]: continue
        used[v] = True; n_used += 1; edges.append((u, v))
        weight += c
        for w, d in E[v].items():
            if not used[w]: heappush(heap, (d, v, w))
    return edges, weight

N = int(input())
cities = [(a, b, i) for i, (a, b) in enumerate([tuple(map(int, input().split())) for _ in range(N)])]
sorted_x, sorted_y = sorted(cities, key=lambda x:x[0]), sorted(cities, key=lambda x:x[1])
E = {i: defaultdict(int) for i in range(N)}
for i in range(N-1):
    (a1, _, u), (a2, _, v) = sorted_x[i], sorted_x[i+1]
    E[u][v], E[v][u] = a2 - a1, a2 - a1
    (_, b1, u), (_, b2, v) = sorted_y[i], sorted_y[i+1]
    E[u][v], E[v][u] = min(b2 - b1, E[u][v]), min(b2 - b1, E[v][u])
V = list(range(N))
_, ans = prim(V, E)
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import *
from collections import defaultdict

def prim(V, E):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
    Output:
        the edges of the minimum weight tree and its weight
    '''
    N = len(V)
    weight = 0; edges = [];
    used = [False]*N; used[0] = True; n_used = 1;
    heap = [(c, 0, v) for v, c in E[0].items()]; heapify(heap)
    while heap and n_used < N:
        c, u, v = heappop(heap)
        if used[v]: continue
        used[v] = True; n_used += 1; edges.append((u, v))
        weight += c
        for w, d in E[v].items():
            if not used[w]: heappush(heap, (d, v, w))
    return edges, weight

N = int(input())
cities = [(a, b, i) for i, (a, b) in enumerate([tuple(map(int, input().split())) for _ in range(N)])]
N = len(cities)
sorted_x, sorted_y = sorted(cities, key=lambda x:x[0]), sorted(cities, key=lambda x:x[1])
E = {i: defaultdict(int) for i in range(N)}
for i in range(N-1):
    (a1, _, u), (a2, _, v) = sorted_x[i], sorted_x[i+1]
    E[u][v] = E[v][u] = a2 - a1
    (_, b1, u), (_, b2, v) = sorted_y[i], sorted_y[i+1]
    E[u][v] = E[v][u] = b2 - b1
V = list(range(N))
_, ans = prim(V, E)
print(ans)

Submission status: Wrong Answer

Solution code:
from heapq import *
from collections import defaultdict

def prim(V, E):
    '''
    Input:
        V = list(range(N))
        E = {i: defaultdict(int) for i in range(N)}
    Output:
        the edges of the minimum weight tree and its weight
    '''
    N = len(V)
    weight = 0; edges = [];
    used = [False]*N; used[0] = True; n_used = 1;
    heap = [(c, 0, v) for v, c in E[0].items()]; heapify(heap)
    while heap and n_used < N:
        c, u, v = heappop(heap)
        if used[v]: continue
        used[v] = True; n_used += 1; edges.append((u, v))
        weight += c
        for w, d in E[v].items():
            if not used[w]: heappush(heap, (d, v, w))
    return edges, weight

N = int(input())
cities = [(a, b, i) for i, (a, b) in enumerate(set([tuple(map(int, input().split())) for _ in range(N)]))]
N = len(cities)
sorted_x, sorted_y = sorted(cities, key=lambda x:x[0]), sorted(cities, key=lambda x:x[1])
E = {i: defaultdict(int) for i in range(N)}
for i in range(N-1):
    (a1, _, u), (a2, _, v) = sorted_x[i], sorted_x[i+1]
    E[u][v] = E[v][u] = a2 - a1
    (_, b1, u), (_, b2, v) = sorted_y[i], sorted_y[i+1]
    E[u][v] = E[v][u] = b2 - b1
V = list(range(N))
_, ans = prim(V, E)
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    city = []
    for i in range(n):
        x,y = map(int, input().split())
        city.append((x,y,i))
    edges = []
    # x
    city.sort()
    for i in range(n-1):
        dist = city[i+1][0] - city[i][0]
        edges.append((dist, city[i][2], city[i+1][2]))
    # y
    city.sort(key=lambda x:x[1])
    for i in range(n-1):
        dist = city[i+1][1] - city[i][1]
        edges.append((dist, city[i][2], city[i+1][2]))

    s = set()
    edges.sort()
    ans = 0
    cnt = 0
    while len(s) < n:
        dist, from_, to = edges[cnt]
        if from_ not in s or to not in s:
            s.add(from_)
            s.add(to)
            ans += dist
        cnt += 1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import heapq
def prim_heap():
    used = [True] * n #True:不使用
    edgelist = []
    for e in edge[0]:
        heapq.heappush(edgelist,e)
    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
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,e)
        res += minedge[0]
    return res

#########################
n = int(input())

#隣接リストの作成 edge[i]:[コスト,行先]
edge = [[] for i in range(n)]
p = []
p=[]
d=[[] for i in range(n)]
for i in range(n):
    p.append(tuple(map(int,input().split()))+tuple([i]))
x_sort=sorted(p,key=lambda x:x[0])
y_sort=sorted(p,key=lambda x:x[1])
for i in range(1,n):
    edge[x_sort[i][2]].append([min(abs(x_sort[i][0]-x_sort[i-1][0]),abs(x_sort[i][1]-x_sort[i-1][1])),x_sort[i-1][2]])
    edge[x_sort[i-1][2]].append([min(abs(x_sort[i][0]-x_sort[i-1][0]),abs(x_sort[i][1]-x_sort[i-1][1])),x_sort[i][2]])
    edge[y_sort[i][2]].append([min(abs(y_sort[i][0]-y_sort[i-1][0]),abs(y_sort[i][1]-y_sort[i-1][1])),y_sort[i-1][2]])
    edge[y_sort[i][2]].append([min(abs(y_sort[i][0]-y_sort[i-1][0]),abs(y_sort[i][1]-y_sort[i-1][1])),y_sort[i-1][2]])
print(prim_heap())

Submission status: Wrong Answer

Solution code:
import heapq
def prim_heap():
    used = [True] * n #True:不使用
    edgelist = []
    for e in edge[0]:
        heapq.heappush(edgelist,e)
    used[0] = False
    res = 0
    counter = 1
    while counter != n:
        minedge = heapq.heappop(edgelist)
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,e)
        res += minedge[0]
        counter += 1
    return res

#########################
n = int(input())

#隣接リストの作成 edge[i]:[コスト,行先]
edge = [[] for i in range(n)]
p = []
p=[]
for i in range(n):
    p.append(tuple(map(int,input().split()))+tuple([i]))
x_sort=sorted(p,key=lambda x:x[0])
y_sort=sorted(p,key=lambda x:x[1])
for i in range(1,n):
    edge[x_sort[i][2]].append([min(abs(x_sort[i][0]-x_sort[i-1][0]),abs(x_sort[i][1]-x_sort[i-1][1])),x_sort[i-1][2]])
    edge[x_sort[i-1][2]].append([min(abs(x_sort[i][0]-x_sort[i-1][0]),abs(x_sort[i][1]-x_sort[i-1][1])),x_sort[i][2]])
    edge[y_sort[i][2]].append([min(abs(y_sort[i][0]-y_sort[i-1][0]),abs(y_sort[i][1]-y_sort[i-1][1])),y_sort[i-1][2]])
    edge[y_sort[i][2]].append([min(abs(y_sort[i][0]-y_sort[i-1][0]),abs(y_sort[i][1]-y_sort[i-1][1])),y_sort[i-1][2]])
print(prim_heap())

Submission status: Wrong Answer

Solution code:
import numpy
N=int(input())
len = [list(map(int,input().split())) for t in range (N)]
a=[]
ans=0
for i in range (N):
    for j in range (N):
        if i <= j:
            a.append(abs(len[i][1]-len[j][1]))
        else:
            a.append(abs(len[i][0]-len[j][0]))

b=[i for i in range(N)]
a=[max(a)+1 if i==0 else i for i in a]

while all((x == b[0]  for x in b))==False:
    c=min(a)
    for i in range (N*N):
        if b[i//N] != b[i%N]:
            if a[i]==min(a):
                ans+=a[i]
                a[i//N+i%N*N]=max(a) #反対側のつなぎ方を0に
                a[i]=max(a)
                b=[b[i//N] if x==b[i%N] else x for x in b]
    else:
        if c == min(a):
            a=[max(a) if y==min(a) else y for y in a]

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy
N=int(input())
len = [list(map(int,input().split())) for t in range (N)]
a=[]
ans=0
for i in range (N):
    for j in range (N):
        if i <= j:
            a.append(abs(len[i][1]-len[j][1]))
        else:
            a.append(abs(len[i][0]-len[j][0]))

b=[i for i in range(N)]
a=[max(a)+1 if i==0 else i for i in a]

while all((x == b[0]  for x in b))==False:
    c=min(a)
    for i in range (N*N):
        if a[i]==min(a):
            if b[i//N] != b[i%N]:
                ans+=a[i]
                a[i//N+i%N*N]=max(a) #反対側のつなぎ方を0に
                a[i]=max(a)
                b=[b[i//N] if x==b[i%N] else x for x in b]
    else:
        if c == min(a):
            a=[max(a) if y==min(a) else y for y in a]
            
print(ans)

Submission status: Wrong Answer

Solution code:
import sys
N=int(input())
len = [list(map(int,input().split())) for t in range (N)]

a=0
for i in range (N-1):
    print(len[i][0],len[i+1][0],len[i][1],len[i+1][1])
    a+=min(abs(len[i][0]-len[i+1][0]),abs(len[i][1]-len[i+1][1]))

print(a)

Submission status: Wrong Answer

Solution code:
from operator import itemgetter

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

	def find(self, x):
		while self.table[x] >= 0:
			x = self.table[x]
		return 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[s2] = s1
			elif self.table[s1] < self.table[s2]:
				self.table[s1] = s2
			else:
				self.table[s1] = s2
				self.table[s2] -= 1
		return

n = int(input())
xy = [list(map(int, input().split())) for _ in range(n)]
xy_x = {i: xy[i][0] for i in range(n)}
xy_y = {i: xy[i][1] for i in range(n)}

v_x = sorted(xy_x.items(), key=itemgetter(1))
v_y = sorted(xy_y.items(), key=itemgetter(1))

edges = dict()

for i in range(n - 1):
	edges[(v_x[i][0], v_x[i+1][0])] = v_x[i+1][1] - v_x[i][1]
	edges[(v_y[i][0], v_y[i+1][0])] = v_y[i+1][1] - v_y[i][1]

uf = UnionFind(n)

edges = sorted(edges.items(), key=itemgetter(1))

ans = 0

while edges != list():
	e = edges.pop(0)
	if uf.find(e[0][0]) != uf.find(e[0][1]):
		uf.union(e[0][0], e[0][1])
		ans += e[1]

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import defaultdict

class UnionFind(object):
  def __init__(self,n):
    self.table=[-1]*n
 
  def find(self,x):
    parent=self.table[x]
    if parent<0:
      return x
    else:
      root=self.find(parent)
      self.table[x]=root
      return root
 
  def union(self,a,b):
    root1=self.find(a)
    root2=self.find(b)
    if root1 != root2:
      if self.table[root1] != self.table[root2]:
        if self.table[root1] < self.table[root2]:
          self.table[root2]=root1
        else:
          self.table[root1]=root2
      else:
        self.table[root1]+=(-1)
        self.table[root2]=root1

N=int(input())
x=[]
y=[]
M=defaultdict(int)
for i in range(N):
  X,Y=map(int,input().split())
  x.append((i,X))
  y.append((i,Y))

x=sorted(x,key=lambda x:x[1])
y=sorted(y,key=lambda y:y[1])

for i in range(N-1):
  a,b=x[i]
  c,d=y[i]
  e,f=x[i+1]
  g,h=y[i+1]
  if M[(a,e)]!=0:
    M[(a,e)]=min(M[(a,e)],f-b)
  else:
    M[(a,e)]=f-b
  if M[(c,g)]!=0:
    M[(c,g)]=min(M[(c,g)],h-d)
  else:
    M[(c,g)]=h-d

uf=UnionFind(N)
ans=0

for a,b in sorted(M.items(),key=lambda x:x[1]):
  s,t=a
  if uf.find(s)!=uf.find(t):
    uf.union(s,t)
    ans+=b

print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N=int(input())
x=[0 for i in range(N)]
y=[0 for i in range(N)]
for i in range(N):
    x[i],y[i]=map(int,input().split())
s=list(np.argsort(np.array(x)))
t=list(np.argsort(np.array(y)))
L=[]
R=[]
def norm(i,j):
    return min([abs(x[i]-x[j]),abs(y[i]-y[j])])
for i in range(N-1):
    L.append(norm(s[i],s[i+1]))
    R.append((s[i],s[i+1]))
    L.append(norm(t[i],t[i+1]))
    R.append((t[i],t[i+1]))
u=list(np.argsort(np.array(L)))
S=set()
M=0
for i in range(2*N-2):
    if not(R[u[i]][0] in S and R[u[i]][1] in S):
        S.add(R[u[i]][0])
        S.add(R[u[i]][1])
        M+=L[u[i]]
print(M)

Submission status: Wrong Answer

Solution code:
import numpy as np
N=int(input())
x=[0 for i in range(N)]
y=[0 for i in range(N)]
for i in range(N):
  x[i],y[i]=map(int,input().split())
s=list(np.argsort(np.array(x)))
t=list(np.argsort(np.array(y)))
L=[]
R=[]
def norm(i,j):
  return min([abs(x[i]-x[j]),abs(y[i]-y[j])])
for i in range(N-1):
  L.append(norm(s[i],s[i+1]))
  R.append((s[i],s[i+1]))
  L.append(norm(t[i],t[i+1]))
  R.append((t[i],t[i+1]))
u=list(np.argsort(np.array(L)))
S=set()
M=0
for i in range(2*N-2):
  if not(set(R[u[i]])<=S):
    S.add(R[u[i]][0])
    S.add(R[u[i]][1])
    M+=L[u[i]]
print(M)

Submission status: Wrong Answer

Solution code:
import numpy as np
N=int(input())
x=[0 for i in range(N)]
y=[0 for i in range(N)]
for i in range(N):
  x[i],y[i]=map(int,input().split())
s=list(np.argsort(np.array(x)))
t=list(np.argsort(np.array(y)))
L=[]
R=[]
def norm(i,j):
  return abs(x[i]-x[j])+abs(y[i]-y[j])
for i in range(N-1):
  L.append(norm(s[i],s[i+1]))
  R.append((s[i],s[i+1]))
  L.append(norm(t[i],t[i+1]))
  R.append((t[i],t[i+1]))
u=list(np.argsort(np.array(L)))
S=set()
M=0
for i in range(2*N-2):
  if not(set(R[u[i]])<=S):
    S.add(R[u[i]][0])
    S.add(R[u[i]][1])
    M+=L[u[i]]
print(M)

Submission status: Wrong Answer

Solution code:
n = int(input())
xs = []
ys = []

for i in range(n):
    x, y = map(int, input().split())
    xs.append((x, i))
    ys.append((y, i))


xs.sort()
ys.sort()

es = []

for i in range(n-1):
    es.append((xs[i+1][0] - xs[i][0], xs[i][1], xs[i+1][1]))
    es.append((ys[i+1][0] - ys[i][0], ys[i][1], ys[i+1][1]))

es.sort()
print(0)
exit()

class UF:
    def __init__(self):
        self.p = {}
    def find(self, x):
        if x not in self.p:
            self.p[x] = x
        if x == self.p[x]:
            return x
        self.p[x] = self.find(self.p[x])
        return self.p[x]
    def merge(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            self.p[x] = y


uf= UF()
ans = 0
for d, i0, i1 in es:
    c0 = uf.find(i0)
    c1 = uf.find(i1)
    if c0 == c1:
        continue
    ans += d
    uf.merge(i0, i1)
print(ans)

Submission status: Wrong Answer

Solution code:
length = int(input())
target = []
for i in range(length):
    a,b = (int(n) for n in input().split(" "))
    target.append([a,b,i])
target.sort()
bef_x,bef_y = -1,-1
for i in range(length-1,-1,-1):
    if bef_x == target[i][0] and bef_y == target[i][1]:
        target.pop(i)
        length -= 1
    else:
        bef_x = target[i][0]
        bef_y = target[i][1]

x_sorted = target[:]
y_sorted = (sorted(target,key=lambda x:x[1]))[:]
count = 0
already = set()
now_x = 0
now_y = 0
now_rev_x = length - 1
now_rev_y = length - 1
answer = 0
# print(x_sorted)
# print(y_sorted)
while count < length - 1:

    x_diff = abs(x_sorted[now_x][0] - x_sorted[now_x + 1][0])
    rev_x_diff = abs(x_sorted[now_rev_x][0] - x_sorted[now_rev_x - 1][0])
    y_diff = abs(y_sorted[now_y][1] - y_sorted[now_y + 1][1])
    rev_y_diff = abs(y_sorted[now_rev_y][1] - y_sorted[now_rev_y - 1][1])

    min_choice = min(x_diff,rev_x_diff,y_diff,rev_y_diff)

    if min_choice == x_diff:
        real_index = {x_sorted[now_x][2],x_sorted[now_x + 1][2]}
        if (real_index - already):
            answer += min_choice
            already |= real_index
            now_x += 1
        else:
            now_x += 1
    elif min_choice == y_diff:
        real_index = {y_sorted[now_y][2],y_sorted[now_y + 1][2]}
        if (real_index - already):
            answer +=  min_choice
            already |= real_index
            now_y += 1
        else:
            now_y += 1

    elif min_choice == rev_x_diff:
        real_index = {x_sorted[now_rev_x][2],x_sorted[now_rev_x - 1][2]}
        if (real_index - already):
            answer += min_choice
            already |= real_index
            now_rev_x -= 1
        else:
            now_rev_x -= 1
    else:
        real_index = {y_sorted[now_rev_y][2],y_sorted[now_rev_y - 1][2]}
        if (real_index - already):
            answer +=  min_choice
            already |= real_index
            now_rev_y -= 1
        else:
            now_rev_y -= 1
    if now_x == now_rev_x:
        x_sorted[now_x][0] = float("inf")
    elif now_y == now_rev_y:
        y_sorted[now_y][1] = float("inf")
    # print(x_diff,rev_x_diff,y_diff,rev_y_diff,now_x,now_rev_x,now_y,now_rev_y,answer,already)
    count += 1
print(answer)

Submission status: Wrong Answer

Solution code:
length = int(input())
target = []
for i in range(length):
    a,b = (int(n) for n in input().split(" "))
    target.append([a,b,i])
target.sort()
bef_x,bef_y = -1,-1
for i in range(length-1,-1,-1):
    if bef_x == target[i][0] and bef_y == target[i][1]:
        target.pop(i)
        length -= 1
    else:
        bef_x = target[i][0]
        bef_y = target[i][1]

x_sorted = target[:]
y_sorted = (sorted(target,key=lambda x:x[1]))[:]
count = 0
already = set()
now_x = 0
now_y = 0
now_rev_x = length - 1
now_rev_y = length - 1
answer = 0
# print(x_sorted)
# print(y_sorted)
while count < length - 1:

    x_diff = abs(x_sorted[now_x][0] - x_sorted[now_x + 1][0])
    rev_x_diff = abs(x_sorted[now_rev_x][0] - x_sorted[now_rev_x - 1][0])
    y_diff = abs(y_sorted[now_y][1] - y_sorted[now_y + 1][1])
    rev_y_diff = abs(y_sorted[now_rev_y][1] - y_sorted[now_rev_y - 1][1])

    min_choice = min(x_diff,rev_x_diff,y_diff,rev_y_diff)

    if min_choice == x_diff:
        if ({now_x,now_x - 1} - already):
            answer += min_choice
            now_x += 1
            already |= {now_x,now_x - 1}
        else:
            now_x += 1
    elif min_choice == y_diff:
        if ({now_y,now_y + 1} - already):
            answer +=  min_choice
            already |= {now_y,now_y + 1}
            now_y += 1
        else:
            now_y += 1

    elif min_choice == rev_x_diff:
        if ({now_rev_x,now_rev_x - 1} - already):
            answer += min_choice
            already |= {now_rev_x,now_rev_x - 1}
            now_rev_x -= 1
        else:
            now_rev_x -= 1
    else:
        if ({now_rev_y,now_rev_y - 1} - already):
            answer +=  min_choice
            already |= {now_rev_y,now_rev_y - 1}
            now_rev_y -= 1
        else:
            now_rev_y -= 1
    if now_x == now_rev_x:
        x_sorted[now_x] = float("inf")
    elif now_y == now_rev_y:
        y_sorted[now_y] = float("inf")
    # print(x_diff,rev_x_diff,y_diff,rev_y_diff,now_x,now_rev_x,now_y,now_rev_y,answer,already)
    count += 1
print(answer)

Submission status: Wrong Answer

Solution code:
import numpy as np

N=int(input())
pos_mat=np.zeros((N,2))
for i in range(N):
    buf=input().split()
    pos_mat[i,0]=int(buf[0])
    pos_mat[i,1]=int(buf[1])

#cost_mat=np.zeros((N,N))
#for u in range(N):
#    for v in range(u+1, N):
#        cost_mat[u,v]=min(abs(pos_mat[u, 0]-pos_mat[v,0]), abs(pos_mat[u, 1]-pos_mat[v,1]))

print(0)

Submission status: Wrong Answer

Solution code:
import sys
n = int(raw_input())
e = [[int(i) for i in raw_input().split()] for i in range(n)]
m = n
li = []
for i in range(n):
    for j in range(i, n):
        if i == j: continue
        li.append(min(abs(e[i][0] - e[j][0]), abs(e[i][1] - e[j][1])))
li.sort()
ans = 0
for i in range(n-1):
    ans += li[i]
print ans

Submission status: Wrong Answer

Solution code:
N = int(input())
x,y = [],[]
INF = 100000000000
for i in range(N):
    s,t = [int(k) for k in input().split(" ")]
    x.append(s)
    y.append(t)
dic_x = {}
dic_y = {}
for i in range(N):
    for j in range(i+1,N):
        dic_x[(i,j)] = abs(x[i]-x[j])
        dic_y[(i,j)] = abs(y[i]-y[j])
edge_x=[]
for key,value in sorted(dic_x.items(),key=lambda s:s[1]):
    edge_x.append(key)
edge_y=[]
for key,value in sorted(dic_y.items(),key=lambda s:s[1]):
    edge_y.append(key)
itr_x = 0
itr_y = 0
V = []
ans=0
while len(V) != N :
    if dic_x[edge_x[itr_x]] < dic_y[edge_y[itr_y]]:
        i = edge_x[itr_x][0]
        j = edge_x[itr_x][1]
        itr_x += 1
        if (i in V) == False and (j in V) == False:
            V.append(i)
            V.append(j)
            ans += dic_x[(i,j)]
        elif (i in V) == False:
            V.append(i)
            ans += dic_x[(i,j)]
        elif (j in V) == False:
            V.append(j)
            ans += dic_x[(i,j)]
    else:
        i = edge_y[itr_y][0]
        j = edge_y[itr_y][1]
        itr_y += 1
        if (i in V) == False and (j in V) == False:
            V.append(i)
            V.append(j)
            ans += dic_y[(i,j)]
        elif (i in V) == False:
            V.append(i)
            ans += dic_y[(i,j)]
        elif (j in V) == False:
            V.append(j)
            ans += dic_y[(i,j)]
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np
N = int(input())
loc = np.array([[0,0]], dtype = "int32")
for i in range(N):
    tmp = np.array([int(j) for j in input().split()]).reshape(1,2)
    loc = np.append(loc, tmp, axis = 0)

    
mat = np.zeros((N,N), dtype = "int32")
for i in range(N):
    for j in range(N):
        mat[i,j] = np.min(abs(loc[i]-loc[j]))
        if i == j:
            mat[i,j] = int(1e9)
res = np.min(mat, axis = 0)
print(np.sum(res))

Submission status: Wrong Answer

Solution code:
# coding: utf-8
import array, bisect, collections, copy, heapq, itertools, math, random, re, string, sys, time
sys.setrecursionlimit(10 ** 7)
INF = 10 ** 20
MOD = 10 ** 9 + 7


def II(): return int(input())
def ILI(): return list(map(int, input().split()))
def IAI(LINE): return [ILI() for __ in range(LINE)]
def IDI(): return {key: value for key, value in ILI()}


def read():
    N = II()
    x_y = [ILI() for __ in range(N)]
    return N, x_y


def solve(N, x_y):
    left_point = x_y[0]
    right_point = x_y[1]
    point_len = min(abs(left_point[0] - right_point[0]), abs(left_point[1] - right_point[1]))
    for i in range(2, N):
        now_point = x_y[i]
        left_len = min(abs(left_point[0] - now_point[0]), abs(left_point[1] - now_point[1]))
        right_len = min(abs(left_point[0] - now_point[0]), abs(left_point[1] - now_point[1]))
        if left_len <= point_len:
            continue
        if right_len <= point_len:
            continue
        point_len = max(left_len, right_len)
        right_point = now_point
    
    return point_len
    


def main():
    params = read()
    print(solve(*params))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype='int64')
Y = np.zeros(N, dtype='int64')

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    
# sort edges
sel = np.argsort(np.array(edge_weight, dtype='int64'))

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    if flg[m]*flg[n] > 0:
        pass
    else:
        res += edge_weight[s]
        flg[m] = 1
        flg[n] = 1
print(res)

Submission status: Wrong Answer

Solution code:
# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype=int)
Y = np.zeros(N, dtype=int)

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    
# sort edges
sel = np.argsort(np.array(edge_weight))

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    if flg[m]*flg[n] > 0:
        pass
    else:
        res += edge_weight[s]
        flg[m] = 1
        flg[n] = 1
print(res)