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: Time Limit Exceeded

Solution code:
class unionfind:
    def __init__(self, n):
        self.n = n
        self.root = [-1]*(n+1)
        self.rnk = [0]*(n+1)
    def find(self, x):
        if(self.root[x] < 0):
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]
    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if(x == y):
            return 
        elif(self.rnk[x] > self.rnk[y]):
            self.root[x] += self.root[y]
            self.root[y] = x
        else:
            self.root[y] += self.root[x]
            self.root[x] = y
            if(self.rnk[x] == self.rnk[y]):
                self.rnk[y] += 1
    def same(self, x, y):
        return self.find(x) == self.find(y)
    def count(self, x):
        return -self.root[self.find(x)]
import sys
input=sys.stdin.readline
n=int(input())
l=sorted([tuple(map(int,input().split())) for i in range(n)])
import collections
d=collections.defaultdict(int)
j=1
for i in l:
    if d[i]==0:
        d[i]=j
        j+=1
from heapq import heappush,heappop
pq=[]
for i in range(n-1):
    c=l[i+1][0]-l[i][0]
    heappush(pq,(c,l[i],l[i+1]))
l.sort(key=lambda x:x[1])
for i in range(n-1):
    c=l[i+1][1]-l[i][1]
    heappush(pq,(c,l[i],l[i+1]))
ans=0
uf=unionfind(n)
while pq:
    c,x,y=heappop(pq)
    x,y=d[x],d[y]
    if not uf.same(x,y):
        ans+=c
        uf.unite(x,y)
print(ans)

Submission status: Time Limit Exceeded

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

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 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()


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

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

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

        if x == y:
            return

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

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

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

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def main():
    N = I()
    points = []
    G = [[] for _ in range(N)]
    Point = collections.namedtuple('Point', ['n', 'x', 'y'])
    Edge = collections.namedtuple('Edge', ['fr', 'to', 'cost'])
    for i in range(N):
        x, y = LI()
        points.append(Point(i, x, y))
    x_sorted = sorted(points, key=lambda p: p.x)
    y_sorted = sorted(points, key=lambda p: p.y)
    edges = []
    for i in range(N-1):
        p1, p2 = x_sorted[i], x_sorted[i+1]
        cost = p2.x - p1.x
        assert cost >= 0
        edges.append(Edge(p1.n, p2.n, cost))
        edges.append(Edge(p2.n, p1.n, cost))

        p3, p4 = y_sorted[i], y_sorted[i+1]
        cost = p4.y - p3.y
        assert cost >= 0
        edges.append(Edge(p3.n, p4.n, cost))
        edges.append(Edge(p4.n, p3.n, cost))

    # E = 2V, let's prim
    sorted_edge = sorted(edges, key=lambda x: x.cost)
    uf = UnionFind(N)
    res = 0
    for i in range(len(sorted_edge)):
        edge = sorted_edge[i]
        if not uf.same(edge.fr, edge.to):
            uf.union(edge.fr, edge.to)
            res += edge.cost
    print(res)

main()

Submission status: Time Limit Exceeded

Solution code:
import queue,sys,copy
sys.setrecursionlimit(10**7)
INF = 10**10
N = int(input())
x = [0 for _ in range(N)]
y = [0 for _ in range(N)]
for i in range(N):
    x[i], y[i] = map(int,input().split())
ix = [i for i in range(N)]
sort_x_ix = sorted(ix, key=lambda i:x[i])
sort_x = [x[i] for i in sort_x_ix]
sort_y_ix = sorted(ix, key=lambda i:y[i])
sort_y = [y[i] for i in sort_y_ix]

g = [i for i in range(N+1)]
def root(x):
    if g[x] == x : return x
    g[x] = root(g[x])
    return g[x]
q = []
for i in range(N-1):
    q.append((sort_x[i+1]-sort_x[i],sort_x_ix[i],sort_x_ix[i+1]))
    q.append((sort_y[i+1]-sort_y[i],sort_y_ix[i],sort_y_ix[i+1]))

q.sort()
ans = 0
cnt = N

for d,s,t in q:
    if cnt <= 1: break
    if root(s) != root(t):
        ans += d
        cnt -= 1
        g[root(t)] = g[s]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue,sys,copy
sys.setrecursionlimit(10**7)
INF = 10**10
N = int(input())
x = [-INF] + [0 for _ in range(N)] + [INF]
y = [-INF] + [0 for _ in range(N)] + [INF]
for i in range(1,N+1):
    x[i], y[i] = map(int,input().split())
ix = [i for i in range(N+2)]
sort_x_ix = sorted(ix, key=lambda i:x[i])
sort_x = [x[i] for i in sort_x_ix]
sort_y_ix = sorted(ix, key=lambda i:y[i])
sort_y = [y[i] for i in sort_y_ix]
sort_x_inv = [0 for _ in range(N+2)]
sort_y_inv = [0 for _ in range(N+2)]
for i in range(N+2):
    sort_x_inv[sort_x_ix[i]] = i
    sort_y_inv[sort_y_ix[i]] = i

g = [i for i in range(N+1)]
def root(x):
    if g[x] == x : return x
    g[x] = root(g[x])
    return g[x]
q = queue.PriorityQueue()

z = N//2
def put_xy(z):
    i_x = sort_x_inv[z]
    i_y = sort_y_inv[z]
    q.put((sort_x[i_x] - sort_x[i_x-1],z,sort_x_ix[i_x-1]))
    q.put((sort_x[i_x+1] - sort_x[i_x],z,sort_x_ix[i_x+1]))
    q.put((sort_y[i_y] - sort_y[i_y-1],z,sort_y_ix[i_y-1]))
    q.put((sort_y[i_y+1] - sort_y[i_y],z,sort_y_ix[i_y+1]))

put_xy(z)
ans = 0
cnt = N

while True:
    if cnt <= 1: break
    d,s,t = q.get()
    if root(s) != root(t):
        ans += d
        cnt -= 1
        g[t] = g[s]
        put_xy(t)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue,sys,copy
sys.setrecursionlimit(10**7)
INF = 10**10
N = int(input())
x = [0 for _ in range(N)]
y = copy.deepcopy(x)
for i in range(N):
    x[i], y[i] = map(int,input().split())
ix = [i for i in range(N)]
sort_x_ix = sorted(ix, key=lambda i:x[i])
sort_x = [x[i] for i in sort_x_ix]
sort_y_ix = sorted(ix, key=lambda i:y[i])
sort_y = [y[i] for i in sort_y_ix]

g = [i for i in range(N+1)]
def root(x):
    if g[x] == x : return x
    g[x] = root(g[x])
    return g[x]
q = []
for i in range(N-1):
    q.append((sort_x[i+1]-sort_x[i],sort_x_ix[i],sort_x_ix[i+1]))
    q.append((sort_y[i+1]-sort_y[i],sort_y_ix[i],sort_y_ix[i+1]))
q.sort()
ans = 0
cnt = N
for d,s,t in q:
    if cnt <= 1: break
    if root(s) != root(t):
        ans += d
        cnt -= 1
        g[g[t]] = g[s]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import queue,sys
sys.setrecursionlimit(10**7)
INF = 10**10
N = int(input())
x = [0 for _ in range(N)]
y = [0 for _ in range(N)]
for i in range(N):
    x[i], y[i] = map(int,input().split())
x_ix = [i for i in range(N)]
y_ix = [i for i in range(N)]
sort_x_ix = sorted(x_ix, key=lambda i:x[i])
sort_x = [x[i] for i in sort_x_ix]
sort_y_ix = sorted(y_ix, key=lambda i:y[i])
sort_y = [y[i] for i in sort_y_ix]

g = [i for i in range(N+1)]
def root(x):
    if g[x] == x : return x
    g[x] = root(g[x])
    return g[x]
q = []
for i in range(N-1):
    q.append((sort_x[i+1]-sort_x[i],sort_x_ix[i],sort_x_ix[i+1]))
    q.append((sort_y[i+1]-sort_y[i],sort_y_ix[i],sort_y_ix[i+1]))
q.sort()
ans = 0
cnt = N
for d,s,t in q:
    if cnt <= 1: break
    if root(s) != root(t):
        ans += d
        cnt -= 1
        g[root(t)] = g[s]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
data = []
class UnionFind:
    def __init__(self, n):
        #親ノードの番号を格納
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.size = [1] * (n+1)
    def find(self, x):
        #根ならその番号を返す
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]
    def same_check(self, x, y):
        #同じかどうかの確認
        return self.find(x) == self.find(y)
    def union(self, x, y):
        #統合する
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
            self.size[x] = 0
        elif self.rank[x] > self.rank[y]:
            self.par[y] = x
            self.size[x] += self.size[y]
            self.size[y] = 0
        else:
            self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]
            self.size[y] = 0
    def getsize(self, x):
        p = self.find(x)
        return self.size[p]
x = []
y = []
for i in range(n):
    a,b = map(int, input().split())
    x.append([a,i+1])
    y.append([b,i+1])
x.sort()
y.sort()
edge = []
for i in range(n-1):
    edge.append([x[i+1][0] - x[i][0],x[i+1][1],x[i][1]])
    edge.append([y[i+1][0] - y[i][0],y[i+1][1],y[i][1]])
#edge[i][0] = cost, [1] -> [2]でつながっている辺
edge.sort()
UF = UnionFind(n)
ans = 0
for i in range(len(edge)):
    cost,a,b = edge[i]
    if UF.same_check(a,b):
        continue
    else:
        ans += cost
        UF.union(a,b)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush, heapify
import sys
input = lambda: sys.stdin.readline().rstrip()

def find(x):
    if parents[x] < 0:
        return x
    else:
        parents[x] = find(parents[x])
        return parents[x]
def union(x, y):
    x = find(x)
    y = find(y)

    if x == y:
        return
    if parents[x] > parents[y]:
        x, y = y, x
    parents[x] += parents[y]
    parents[y] = x

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

N = int(input())

verticies_x = []
verticies_y = []

for i in range(N):
    x, y = map(int, input().split())
    verticies_x.append((x,i))
    verticies_y.append((y,i))
verticies_x.sort()    
verticies_y.sort()

edge = []

for i in range(N-1):
    tmp_x = verticies_x[i+1][0] - verticies_x[i][0]
    tmp_y = verticies_y[i+1][0] - verticies_y[i][0]
    heappush(edge, (tmp_x, verticies_x[i][1], verticies_x[i+1][1]))
    heappush(edge, (tmp_y, verticies_y[i][1], verticies_y[i+1][1]))

ans = 0
parents = [-1] * N
while edge:
    cost, s, g = heappop(edge)
    if same(s,g):      
        continue
    else:
        union(s,g)
        ans += cost
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush, heapify
import sys
input = lambda: sys.stdin.readline().rstrip()

class UnionFind:
    def __init__(self, n):
        self.parents = [-1] * n
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

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

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


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

X.sort()
Y.sort()
edge=[]
for i in range(1,N):
    edge.append([X[i][0]-X[i-1][0],X[i-1][1],X[i][1]])
    edge.append([Y[i][0]-Y[i-1][0],Y[i-1][1],Y[i][1]])
edge.sort()
uf = UnionFind(N)
 
ans=0
for l,a,b in edge:
    if uf.same(a,b):
        continue
    else:
        uf.union(a,b)
        ans += l
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def find_parent(x):
    y=parent[x]
    if y<0:
        return x
    parent[x]=find_parent(y)
    return parent[x]

def connect(a,b):
    c=find_parent(a)
    d=find_parent(b)
    if c==d:
        return
    if parent[c]<parent[d]:
        parent[c]+=parent[d]
        parent[d]=c
    else:
        parent[d]+=parent[c]
        parent[c]=d
    return

N=int(input())
X=[]
Y=[]
for i in range(N):
    x,y=map(int,input().split())
    X.append([x,i])
    Y.append([y,i])
X.sort()
Y.sort()
edge=[]
for i in range(1,N):
    edge.append([X[i][0]-X[i-1][0],X[i-1][1],X[i][1]])
    edge.append([Y[i][0]-Y[i-1][0],Y[i-1][1],Y[i][1]])
edge.sort()
parent=[-1]*N
 
ans=0
for l,a,b in edge:
    if find_parent(a)==find_parent(b):
        continue
    else:
        ans+=l
        connect(a,b)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush, heapify

class UnionFind:
    def __init__(self, n):
        self.parents = [-1] * n
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

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

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


N=int(input())
X=[]
Y=[]
for i in range(N):
    x,y=map(int,input().split())
    X.append([x,i])
    Y.append([y,i])
 
X.sort()
Y.sort()
edge=[]
for i in range(1,N):
    edge.append([X[i][0]-X[i-1][0],X[i-1][1],X[i][1]])
    edge.append([Y[i][0]-Y[i-1][0],Y[i-1][1],Y[i][1]])
edge.sort()
uf = UnionFind(N)
 
ans=0
for l,a,b in edge:
    if uf.same(a,b):
        continue
    else:
        uf.union(a,b)
        ans += l
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq



N = int(input())
xy = [None] * N
yx = [None] * N

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


xy.sort()
yx.sort()


es = [[] for _ in range(N)]
for i in range(N-1):
    heapq.heappush(es[xy[i][2]], (abs(xy[i][0] - xy[i+1][0]), xy[i+1][2]))
    heapq.heappush(es[xy[i+1][2]], (abs(xy[i][0] - xy[i+1][0]), xy[i][2]))

    heapq.heappush(es[yx[i][2]], (abs(yx[i][0] - yx[i+1][0]), yx[i+1][2]))
    heapq.heappush(es[yx[i+1][2]], (abs(yx[i][0] - yx[i+1][0]), yx[i][2]))


used = [False] * N
used[0] = True
ans = 0

q = []
for c,nxt in es[0]:
    heapq.heappush(q, (c, nxt))

while q:
    c, curr = heapq.heappop(q)
    
    if used[curr]:
        continue

    used[curr] = True
    for nc, nxt in es[curr]:
        heapq.heappush(q, (nc, nxt))
    ans += c

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#from collections import *
#from itertools import *
#from bisect import *
from heapq import *
#import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

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

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

        if x == y:
            return

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

        self.parents[x] += self.parents[y]
        self.parents[y] = x

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

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

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

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

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N=int(input())

Xsort=[]
Ysort=[]
for i in range(N):
    X,Y=map(int,input().split())
    Xsort.append([X,i])
    Ysort.append([Y,i])
Xsort=sorted(Xsort,key=lambda x:x[0])
Ysort=sorted(Ysort,key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i





def main(i):
    x,y=Nidxlst[i]
    lst=[]
    if x>0:
        a=Xsort[x-1][1]
        m=Xsort[x][0]-Xsort[x-1][0]
        if not uf.same(i,a):
            lst.append([m,a])
    if x<N-1:
        a=Xsort[x+1][1]
        m=Xsort[x+1][0]-Xsort[x][0]
        if not uf.same(i,a):
            lst.append([m,a])
    if y>0:
        a=Ysort[y-1][1]
        m=Ysort[y][0]-Ysort[y-1][0]
        if not uf.same(i,a):
            lst.append([m,a])
    if y<N-1:
        a=Ysort[y+1][1]
        m=Ysort[y+1][0]-Ysort[y][0]
        if not uf.same(i,a):
            lst.append([m,a])
    if lst:
        lst=sorted(lst,key=lambda x:x[0])
        uf.union(i,lst[0][1])
        return(lst[0][0])
value=0
uf=UnionFind(N)
for i in range(N):
    m=main(i)
    if m:
        value+=m
    if uf.group_count()==1:
        break
print(value)

Submission status: Time Limit Exceeded

Solution code:
#from collections import *
#from itertools import *
#from bisect import *
from heapq import *
#import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())

Xsort=[]
Ysort=[]
for i in range(N):
    X,Y=map(int,input().split())
    Xsort.append([X,i])
    Ysort.append([Y,i])
Xsort=sorted(Xsort,key=lambda x:x[0])
Ysort=sorted(Ysort,key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}
def main(x,y):
    if x>0:
        a=Xsort[x-1][1]
        if a in ittenai:
            m=Xsort[x][0]-Xsort[x-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:
        a=Xsort[x+1][1]
        if a in ittenai:
            m=Xsort[x+1][0]-Xsort[x][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:
        a=Ysort[y-1][1]
        if a in ittenai:
            m=Ysort[y][0]-Ysort[y-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:
        a=Ysort[y+1][1]
        if a in ittenai:
            m=Ysort[y+1][0]-Ysort[y][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m

print(value)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())
Xsort=[]
Ysort=[]
for i in range(N):
    X,Y=map(int,input().split())
    Xsort.append([X,i])
    Ysort.append([Y,i])

Xsort=sorted(Xsort,key=lambda x:x[0])
Ysort=sorted(Ysort,key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}
def main(x,y):
    if x>0:
        a=Xsort[x-1][1]
        if a in ittenai:
            m=Xsort[x][0]-Xsort[x-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:
        a=Xsort[x+1][1]
        if a in ittenai:
            m=Xsort[x+1][0]-Xsort[x][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:
        a=Ysort[y-1][1]
        if a in ittenai:
            m=Ysort[y][0]-Ysort[y-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:
        a=Ysort[y+1][1]
        if a in ittenai:
            m=Ysort[y+1][0]-Ysort[y][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m

print(value)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())
XY=[list(map(int,input().split())) for i in range(N)]
Xsort=[]
Ysort=[]
for i in range(N):
    Xsort.append([XY[i][0],i])
    Ysort.append([XY[i][1],i])

Xsort=sorted(Xsort,key=lambda x:x[0])
Ysort=sorted(Ysort,key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}
def main(x,y):
    if x>0:
        a=Xsort[x-1][1]
        if a in ittenai:
            m=Xsort[x][0]-Xsort[x-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:
        a=Xsort[x+1][1]
        if a in ittenai:
            m=Xsort[x+1][0]-Xsort[x][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:
        a=Ysort[y-1][1]
        if a in ittenai:
            m=Ysort[y][0]-Ysort[y-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:
        a=Ysort[y+1][1]
        if a in ittenai:
            m=Ysort[y+1][0]-Ysort[y][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m

print(value)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())
XY=[list(map(int,input().split())) for i in range(N)]
for i in range(N):
    XY[i].append(i)

Xsort=sorted([[i[0],i[2]] for i in XY],key=lambda x:x[0])
Ysort=sorted([[i[1],i[2]] for i in XY],key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}
def main(x,y):
    if x>0:
        a=Xsort[x-1][1]
        if a in ittenai:
            m=Xsort[x][0]-Xsort[x-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:
        a=Xsort[x+1][1]
        if a in ittenai:
            m=Xsort[x+1][0]-Xsort[x][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:
        a=Ysort[y-1][1]
        if a in ittenai:
            m=Ysort[y][0]-Ysort[y-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:
        a=Ysort[y+1][1]
        if a in ittenai:
            m=Ysort[y+1][0]-Ysort[y][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m

print(value)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())
XY=[list(map(int,input().split()))+[i] for i in range(N)]
Xsort=sorted([[i[0],i[2]] for i in XY],key=lambda x:x[0])
Ysort=sorted([[i[1],i[2]] for i in XY],key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}

def main(x,y):
    if x>0:

        a=Xsort[x-1][1]
        if a in ittenai:
            m=Xsort[x][0]-Xsort[x-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:

        a=Xsort[x+1][1]
        if a in ittenai:
            m=Xsort[x+1][0]-Xsort[x][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:

        a=Ysort[y-1][1]
        if a in ittenai:
            m=Ysort[y][0]-Ysort[y-1][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:

        a=Ysort[y+1][1]
        if a in ittenai:
            m=Ysort[y+1][0]-Ysort[y][0]
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m

print(value)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
from bisect import *
from heapq import *
import copy
#N=int(input())
#X,Y=map(int,input().split()))
#S=list(map(int,input().split()))
#S=[list(map(int,input().split())) for i in range(N)]

N=int(input())
XY=[list(map(int,input().split()))+[i] for i in range(N)]
Xsort=sorted([[i[0],i[2]] for i in XY],key=lambda x:x[0])
Ysort=sorted([[i[1],i[2]] for i in XY],key=lambda x:x[0])
Nidxlst=[[0,0] for i in range(N)]
for i in range(N):
    idx=Xsort[i][1]
    Nidxlst[idx][0]=i
    idx=Ysort[i][1]
    Nidxlst[idx][1]=i



value=0
x,y=Nidxlst[0]
ittenai=set([i for i in range(1,N)])

stack=[]
heapify(stack)
setm=set()
dic={}

def main(x,y):
    if x>0:
        m=Xsort[x][0]-Xsort[x-1][0]

        a=Xsort[x-1][1]
        if a in ittenai:
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if x<N-1:
        m=Xsort[x+1][0]-Xsort[x][0]
        a=Xsort[x+1][1]
        if a in ittenai:
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y>0:
        m=Ysort[y][0]-Ysort[y-1][0]
        a=Ysort[y-1][1]
        if a in ittenai:
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
    if y<N-1:
        m=Ysort[y+1][0]-Ysort[y][0]
        a=Ysort[y+1][1]
        if a in ittenai:
            heappush(stack,m)
            if m in setm :
                dic[m].append(a)
            else:
                setm.add(m)
                dic.update({m:[a]})
main(x,y)
idle=10**9+1
value=0
while ittenai:
    m=heappop(stack)
    a=dic[m].pop()
    if a in ittenai:
        x,y=Nidxlst[a]
        main(x,y)
        ittenai.remove(a)
        value+=m    

print(value)