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:
#いろはコンテスト day2
import functools
import sys
from heapq import*
from collections import*

input=sys.stdin.readline


p=defaultdict(lambda: -1)
@functools.lru_cache(maxsize=None)
class UNION_FIND(object):
    def __init__(self,n):
        
        self.parent=defaultdict(lambda: -1)

    def root(self,x):
        if type(self.parent[x])!=tuple:
            return x
        else:
            self.parent[x]=self.root(self.parent[x])
            return self.parent[x]
 
    def size(self,x):
        return -self.parent[self.root(x)]
    def union(self,x,y):
        x=self.root(x)
        y=self.root(y)
        if x==y:
            return False
        if self.size(x)<self.size(y):
            x,y=y,x
        self.parent[x]+=self.parent[y]
        self.parent[y]=x
        return True
def compute_mst_kruskal(max_v, edges, flip):
    edges.sort(key=lambda x: x[2],reverse=flip)
    #print(edges)
    uf = UNION_FIND(max_v)
    mst = []
    for (a,b,c) in edges:
        if uf.root(a)!= uf.root(b):
            uf.union(a,b)
            mst.append(c)
    return mst


n = int(input())
points=[list(map(int,input().split()))for i in range(n)]

x=sorted(points,key=lambda x:x[0])
y=sorted(points,key=lambda x:x[1])
#print(x,y)


edges = []
for i in range(1,n):
    (a,b),(c,d)=x[i-1],x[i]
    (e,f),(g,h)=y[i-1],y[i]
    heappush(edges,((a,b),(c,d),abs(a-c)))
    heappush(edges,((e,f),(g,h),abs(f-h)))
#print(edges)
mst = compute_mst_kruskal(n, edges , 0) #0が最小化
print(sum(mst))

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []

def get_par(n):
    if par[n] is None:return n
    return get_par(par[n])

def same(i,j):
    return get_par(i) == get_par(j)

def unite(i,j):
    j = get_par(j)
    par[j] = get_par(i)
    return

for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    path.append((abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    path.append((abs(y-y2),i,j))
path.sort(key = lambda x:x[0],reverse=True)
par = [None]*N
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = path.pop()
    if same(i,j):continue
    unite(i,j)
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys
sys.setrecursionlimit(100000)
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []

def get_par(n):
    if par[n] is None:return n
    return get_par(par[n])

def same(i,j):
    return get_par(i) == get_par(j)

def unite(i,j):
    j = get_par(j)
    par[j] = get_par(i)
    return

for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    heapq.heappush(path,(abs(y-y2),i,j))
par = [None]*N
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if same(i,j):continue
    unite(i,j)
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys
sys.setrecursionlimit(100000)
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []

def get_par(n):
    if par[n] is None:return n
    return get_par(par[n])

def same(i,j):
    return get_par(i) == get_par(j)

def unite(i,j):
    j = get_par(j)
    par[j] = i
    return

for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    if i>j:i,j = j,i
    heapq.heappush(path,(abs(y-y2),i,j))
par = [None]*N
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if same(i,j):continue
    unite(i,j)
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(y-y2),i,j))
union = [[i] for i in range(N)]
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if union[i] is union[j]:continue
    tmp = union[j][:]
    while tmp:
        k = heapq.heappop(tmp)
        heapq.heappush(union[i],k)
        union[k] = union[i]
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(y-y2),i,j))
union = [[i] for i in range(N)]
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if union[i] is union[j]:continue
    tmp = union[j][:]
    while tmp:
        k = heapq.heappop(tmp)
        union[k] = union[i]
        heapq.heappush(union[i],k)
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(y-y2),i,j))
union = [[i] for i in range(N)]
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if union[i] is union[j]:continue
    while union[j]:
        k = heapq.heappop(union[j])
        if k != j : union[k] = union[i]
        heapq.heappush(union[i],k)
    union[j] = union[i]
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(y-y2),i,j))
union = [[i] for i in range(N)]
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if union[i] is union[j]:continue
    while union[j]:
        k = heapq.heappop(union[j])
        union[k] = union[i]
        heapq.heappush(union[i],k)
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
N=int(input())
xy=[list(map(int,input().split()))+[i] for i in range(N)]
xy.sort()
path = []
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(x-x2),i,j))
xy.sort(key=lambda x:x[1])
for k in range(N-1):
    x,y,i = xy[k]
    x2,y2,j = xy[k+1]
    heapq.heappush(path,(abs(y-y2),i,j))
union = [[i] for i in range(N)]
cnt = 0
ans = 0
while cnt < N-1:
    c,i,j = heapq.heappop(path)
    if union[i] is union[j]:continue
    tmp = union[j].copy()
    while union[j]:
        heapq.heappush(union[i],heapq.heappop(union[j]))
    for k in tmp:
        union[k] = union[i]
    ans += c
    cnt += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
xy = [[i] + list(map(int,input().split())) for i in range(n)]

xy.sort(key=lambda x:x[1])
edge  = []
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((x2-x1,i1,i2))

xy.sort(key=lambda x:x[2])
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((y2-y1,i1,i2))
class UnionFind():
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i in range(N)]
        self.counter = [1] * N

    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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            z = self.counter[x] + self.counter[y]
            self.counter[x], self.counter[y] = z, z
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def size(self, x):
        x = self.find(x)
        return self.counter[x]

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

#クラスカル法
uf = UnionFind(n)
edge.sort()
ans = 0
edge_cnt = 0
i = 0
while edge_cnt < n-1:
    cost,i1,i2 = edge[i]
    if not uf.same(i1,i2):
        ans += cost
        uf.unite(i1,i2)
        edge_cnt += 1
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
from math import*
from collections import deque
from collections import defaultdict
from itertools import permutations
from heapq import*
from collections import Counter
from itertools import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = 10**18
from functools import reduce

n = int(input())
xy = [[i] + list(map(int,input().split())) for i in range(n)]

xy.sort(key=lambda x:x[1])
edge  = []
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((x2-x1,i1,i2))

xy.sort(key=lambda x:x[2])
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((y2-y1,i1,i2))
class UnionFind():
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i in range(N)]
        self.counter = [1] * N

    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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            z = self.counter[x] + self.counter[y]
            self.counter[x], self.counter[y] = z, z
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def size(self, x):
        x = self.find(x)
        return self.counter[x]

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

#クラスカル法
uf = UnionFind(n)
edge.sort()
ans = 0
edge_cnt = 0
i = 0
while edge_cnt < n-1:
    cost,i1,i2 = edge[i]
    if not uf.same(i1,i2):
        ans += cost
        uf.unite(i1,i2)
        edge_cnt += 1
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
from math import*
from collections import deque
from collections import defaultdict
from itertools import permutations
from heapq import*
from collections import Counter
from itertools import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = 10**18
from functools import reduce

n = int(input())
xy = [[i] + list(map(int,input().split())) for i in range(n)]

xy.sort(key=lambda x:x[1])
edge  = []
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((x2-x1,i1,i2))

xy.sort(key=lambda x:x[2])
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((y2-y1,i1,i2))
class UnionFind():
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i in range(N)]
        self.counter = [1] * N

    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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            z = self.counter[x] + self.counter[y]
            self.counter[x], self.counter[y] = z, z
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def size(self, x):
        x = self.find(x)
        return self.counter[x]

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

#クラスカル法
uf = UnionFind(n+1)
edge.sort()
ans = 0
edge_cnt = 0
i = 0
while edge_cnt < n-1:
    cost,i1,i2 = edge[i]
    if not uf.same(i1,i2):
        ans += cost
        uf.unite(i1,i2)
        edge_cnt += 1
    i += 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
from math import*
from collections import deque
from collections import defaultdict
from itertools import permutations
from heapq import*
from collections import Counter
from itertools import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = 10**18
from functools import reduce

n = int(input())
xy = [[i] + list(map(int,input().split())) for i in range(n)]

xy.sort(key=lambda x:x[1])
edge  = []
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((x2-x1,i1,i2))

xy.sort(key=lambda x:x[2])
for i in range(n-1):
    i1,x1,y1 = xy[i]
    i2,x2,y2 = xy[i+1]
    edge.append((y2-y1,i1,i2))
class UnionFind():
    def __init__(self, N):
        self.rank = [0] * N
        self.par = [i for i in range(N)]
        self.counter = [1] * N

    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 unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x != y:
            z = self.counter[x] + self.counter[y]
            self.counter[x], self.counter[y] = z, z
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def size(self, x):
        x = self.find(x)
        return self.counter[x]

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

#クラスカル法
uf = UnionFind(n+1)
edge.sort()
ans = 0
for c,i1,i2 in edge:
    if uf.same(i1,i2):
        continue
    else:
        uf.unite(i1,i2)
        ans += c
print(ans)

Submission status: Time Limit Exceeded

Solution code:
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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

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

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()
E=[]
ans=0
count=1
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=UnionFind(N)
i=0
while(count<N):
    cost,v1,v2=E[i]
    if not U.same_check(v1,v2):
        U.union(v1,v2)
        ans+=cost
        count+=1
    i+=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFindNode(object):
    """
    Union-Find構造
    ノードのグループ併合や、所属グループ判定を高速に処理する
    """

    def __init__(self, group_id, parent=None, value=None):
        self.group_id_ = group_id
        self.parent_ = parent
        self.value = value
        self.size_ = 1

    def __str__(self):
        template = "UnionFindNode(group_id: {}, \n\tparent: {}, value: {}, size: {})"
        return template.format(self.group_id_, self.parent_, self.value, self.size_)

    def is_root(self):
        return not self.parent_

    def root(self):
        parent = self
        while not parent.is_root():
            parent = parent.parent_
            self.parent_ = parent
        return parent

    def find(self):
        parent = self.root()
        return parent.group_id_

    def size(self):
        parent = self.root()
        return parent.size_

    def unite(self, unite_node):
        parent = self.root()
        unite_parent = unite_node.root()

        if parent.group_id_ != unite_parent.group_id_:
            if parent.size() > unite_parent.size():
                unite_parent.parent_ = parent
                parent.size_ = parent.size_ + unite_parent.size_
            else:
                parent.parent_ = unite_parent
                unite_parent.size_ = parent.size_ + unite_parent.size_
    def is_group(self,other):#selfとotherが同じグループに属するか
        return self.root()==other.root()


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()
E=[]
ans=0
count=1
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=[UnionFindNode(i) for i in range(N)]
i=0
while(count<N):
    cost,v1,v2=E[i]
    if not U[v1].is_group(U[v2]):
        U[v1].unite(U[v2])
        ans+=cost
        count+=1
    i+=1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFindNode(object):
    """
    Union-Find構造
    ノードのグループ併合や、所属グループ判定を高速に処理する
    """

    def __init__(self, group_id, parent=None, value=None):
        self.group_id_ = group_id
        self.parent_ = parent
        self.value = value
        self.size_ = 1

    def __str__(self):
        template = "UnionFindNode(group_id: {}, \n\tparent: {}, value: {}, size: {})"
        return template.format(self.group_id_, self.parent_, self.value, self.size_)

    def is_root(self):
        return not self.parent_

    def root(self):
        parent = self
        while not parent.is_root():
            parent = parent.parent_
            self.parent_ = parent
        return parent

    def find(self):
        parent = self.root()
        return parent.group_id_

    def size(self):
        parent = self.root()
        return parent.size_

    def unite(self, unite_node):
        parent = self.root()
        unite_parent = unite_node.root()

        if parent.group_id_ != unite_parent.group_id_:
            if parent.size() > unite_parent.size():
                unite_parent.parent_ = parent
                parent.size_ = parent.size_ + unite_parent.size_
            else:
                parent.parent_ = unite_parent
                unite_parent.size_ = parent.size_ + unite_parent.size_
    def is_group(self,other):#selfとotherが同じグループに属するか
        return self.root()==other.root()


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()
E=[]
ans=0
count=1
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=[UnionFindNode(i) for i in range(N)]
for cost,v1,v2 in E:
    if not U[v1].is_group(U[v2]):
        U[v1].unite(U[v2])
        ans+=cost
        count+=1
        if count==N:
            break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFindNode(object):
    """
    Union-Find構造
    ノードのグループ併合や、所属グループ判定を高速に処理する
    """

    def __init__(self, group_id, parent=None, value=None):
        self.group_id_ = group_id
        self.parent_ = parent
        self.value = value
        self.size_ = 1

    def __str__(self):
        template = "UnionFindNode(group_id: {}, \n\tparent: {}, value: {}, size: {})"
        return template.format(self.group_id_, self.parent_, self.value, self.size_)

    def is_root(self):
        return not self.parent_

    def root(self):
        parent = self
        while not parent.is_root():
            parent = parent.parent_
            self.parent_ = parent
        return parent

    def find(self):
        parent = self.root()
        return parent.group_id_

    def size(self):
        parent = self.root()
        return parent.size_

    def unite(self, unite_node):
        parent = self.root()
        unite_parent = unite_node.root()

        if parent.group_id_ != unite_parent.group_id_:
            if parent.size() > unite_parent.size():
                unite_parent.parent_ = parent
                parent.size_ = parent.size_ + unite_parent.size_
            else:
                parent.parent_ = unite_parent
                unite_parent.size_ = parent.size_ + unite_parent.size_
    def is_group(self,other):#selfとotherが同じグループに属するか
        return self.root()==other.root()


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()
E=[]
ans=0
count=1
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=[UnionFindNode(i) for i in range(N)]
for cost,v1,v2 in E:
    if not U[v1].is_group(U[v2]):
        U[v1].unite(U[v2])
        ans+=cost
        count+=1
    if count==N:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFindNode(object):
    """
    Union-Find構造
    ノードのグループ併合や、所属グループ判定を高速に処理する
    """

    def __init__(self, group_id, parent=None, value=None):
        self.group_id_ = group_id
        self.parent_ = parent
        self.value = value
        self.size_ = 1

    def __str__(self):
        template = "UnionFindNode(group_id: {}, \n\tparent: {}, value: {}, size: {})"
        return template.format(self.group_id_, self.parent_, self.value, self.size_)

    def is_root(self):
        return not self.parent_

    def root(self):
        parent = self
        while not parent.is_root():
            parent = parent.parent_
            self.parent_ = parent
        return parent

    def find(self):
        parent = self.root()
        return parent.group_id_

    def size(self):
        parent = self.root()
        return parent.size_

    def unite(self, unite_node):
        parent = self.root()
        unite_parent = unite_node.root()

        if parent.group_id_ != unite_parent.group_id_:
            if parent.size() > unite_parent.size():
                unite_parent.parent_ = parent
                parent.size_ = parent.size_ + unite_parent.size_
            else:
                parent.parent_ = unite_parent
                unite_parent.size_ = parent.size_ + unite_parent.size_
    def is_group(self,other):#selfとotherが同じグループに属するか
        return self.root()==other.root()


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()
E=[]
ans=0
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=[UnionFindNode(i) for i in range(N)]
for cost,v1,v2 in E:
    if not U[v1].is_group(U[v2]):
        U[v1].unite(U[v2])
        ans+=cost
    if U[v1].size()==N:
        break
print(ans)

Submission status: Time Limit Exceeded

Solution code:
class UnionFindNode(object):
    """
    Union-Find構造
    ノードのグループ併合や、所属グループ判定を高速に処理する
    """

    def __init__(self, group_id, parent=None, value=None):
        self.group_id_ = group_id
        self.parent_ = parent
        self.value = value
        self.size_ = 1

    def __str__(self):
        template = "UnionFindNode(group_id: {}, \n\tparent: {}, value: {}, size: {})"
        return template.format(self.group_id_, self.parent_, self.value, self.size_)

    def is_root(self):
        return not self.parent_

    def root(self):
        parent = self
        while not parent.is_root():
            parent = parent.parent_
            self.parent_ = parent
        return parent

    def find(self):
        parent = self.root()
        return parent.group_id_

    def size(self):
        parent = self.root()
        return parent.size_

    def unite(self, unite_node):
        parent = self.root()
        unite_parent = unite_node.root()

        if parent.group_id_ != unite_parent.group_id_:
            if parent.size() > unite_parent.size():
                unite_parent.parent_ = parent
                parent.size_ = parent.size_ + unite_parent.size_
            else:
                parent.parent_ = unite_parent
                unite_parent.size_ = parent.size_ + unite_parent.size_
    def is_group(self,other):#selfとotherが同じグループに属するか
        return self.root()==other.root()


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()
E=[]
ans=0
for i in range(N-1):
    a=X[i]
    b=X[i+1]
    c=Y[i]
    d=Y[i+1]
    E.extend([(b[0]-a[0],X[i][1],X[i+1][1]),(d[0]-c[0],Y[i][1],Y[i+1][1])])
E.sort()

U=[UnionFindNode(i) for i in range(N)]
for cost,v1,v2 in E:
    if not U[v1].is_group(U[v2]):
        U[v1].unite(U[v2])
        ans+=cost
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
import heapq
N = int(input())
city_ls = list()
for i in range(N):
    city_ls.append([int(i) for i in sys.stdin.readline().split()])
sort_by_x = sorted([[i, j] for i,j in city_ls], key=lambda x:x[0])
sort_by_y = sorted([[j, i] for i,j in city_ls], key=lambda x:x[0])
G = []
id2pos = {i : tuple(j) for i, j in enumerate(city_ls)}
pos2id = {j : i for i, j in id2pos.items()}
for i in range(len(sort_by_x)-1):
    current_by_x = sort_by_x[i]
    next_by_x = sort_by_x[i + 1]
    G.append((abs(current_by_x[0] - next_by_x[0]),current_by_x, next_by_x))
sort_by_x.sort(key=lambda x:x[1])
for i in range(len(sort_by_x) - 1):
    current_by_x = sort_by_x[i]
    next_by_x = sort_by_x[i + 1]
    G.append((abs(current_by_x[1] - next_by_x[1]), current_by_x, next_by_x))
G.sort(key=lambda x:x[0])
sum_cost = 0
par = [i for i in range(N)]
rank = [1 for i in range(N)]
def find(x):
    if par[x] == x:
        return x
    else:
        return find(par[x])

def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        pass
    else:
        if rank[x] > rank[y]:
            par[y] = x
            rank[x] += rank[y]
        else:
            par[x] = par[y]
            rank[y] += rank[x]

def is_same(x, y):
    if find(x) == find(y):
        return True
    else:
        return False

for i in G:
    (cost, _from, _to) = i
    _from = pos2id[tuple(_from)]
    _to = pos2id[tuple(_to)]
    if is_same(_from, _to):
        continue
    unite(_from, _to)
    sum_cost += cost
print(sum_cost)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
import heapq
N = int(input())
city_ls = list()
for i in range(N):
    city_ls.append([int(i) for i in sys.stdin.readline().split()])
sort_by_x = sorted([[i, j] for i,j in city_ls], key=lambda x:x[0])
sort_by_y = sorted([[j, i] for i,j in city_ls], key=lambda x:x[0])
G = []
id2pos = {i : tuple(j) for i, j in enumerate(city_ls)}
pos2id = {j : i for i, j in id2pos.items()}
for i in range(len(sort_by_x)-1):
    current_by_x = sort_by_x[i]
    current_by_y = sort_by_y[i].copy()
    current_by_y.reverse()
    if i < len(sort_by_x) - 1:
        next_by_x = sort_by_x[i + 1]
        next_by_y = sort_by_y[i + 1].copy()
        next_by_y.reverse()
    """
    if G.get(pos2id[current_by_x]) is None:
        G[pos2id[current_by_x]] = []
    if G.get(pos2id[current_by_y.reverse()]) is None:
        G[pos2id[current_by_y.reverse()]] = []
    """
    if i < len(sort_by_x) - 1:
        G.append((abs(current_by_x[0] - next_by_x[0]),current_by_x, next_by_x))
        G.append((abs(current_by_y[1] - next_by_y[1]), current_by_y, next_by_y))
G.sort(key=lambda x:x[0])
sum_cost = 0
par = [i for i in range(N)]
rank = [1 for i in range(N)]
def find(x):
    if par[x] == x:
        return x
    else:
        return find(par[x])

def unite(x, y):
    x = find(x)
    y = find(y)
    if x == y:
        pass
    else:
        if rank[x] > rank[y]:
            par[y] = x
            rank[x] += rank[y]
        else:
            par[x] = par[y]
            rank[y] += rank[x]

def is_same(x, y):
    if find(x) == find(y):
        return True
    else:
        return False

for i in G:
    (cost, _from, _to) = i
    _from = pos2id[tuple(_from)]
    _to = pos2id[tuple(_to)]
    if is_same(_from, _to):
        continue
    unite(_from, _to)
    sum_cost += cost
print(sum_cost)