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:
import heapq
import collections
import heapq
def input_as_int():
    return list(map(int,input().split()))


def get_comb(n):  # n C n まで

    fac = get_fact(n)
    com  = [["error" for _ in range(n+1)] for _ in range (n + 1)]
    for i in range(n + 1):
        for j in range(i + 1):
            if  i >= j:
                com[i][j] = fac[i] // (fac[i-j] * fac[j])

    return com


def get_fact(n):
    temp = 1
    fac = [1]
    for i in range(1, n + 1):
        temp *= i
        fac.append(temp)
    return fac

def prime_method(graph):
    start = graph[0]
    n = len(graph)
    went = [False] * n #n個の点に行ったかという話
    edges = []
    for temp in start:
        heapq.heappush(edges,temp)
    went[0] = True
    cost = 0
    while len(edges) != 0:
        minedge = heapq.heappop(edges)
        if went[minedge[1]]:
            continue
        v = minedge[1]
        for temp in graph[v]:
            if not went[temp[1]]: #その頂点に行ってなければ
                heapq.heappush(edges,temp)
        went[v] = True
        cost += minedge[0]
    return cost
    # a[1] = [[2,3],[5,11]] → 点1からコスト2で頂点3に行ける辺、点1からコスト5で頂点11に行ける辺がある

def get_graph():
    n = input()
    graph = [input_as_int() for _ in range(n)]


    # a[1] = [[2,3],[5,11]] → 点1からコスト2で頂点3に行ける辺、点1からコスト5で頂点11に行ける辺がある


n = int(input())
cities  = [(input_as_int(),i) for i in range(n)]
graph = [[] for _ in  range(n)]

cities.sort(key = lambda x:x[0][0])
citiesX = cities
for city1,city2 in zip(citiesX[0:-1],citiesX[1:]):
    no1 = city1[1]
    no2 = city2[1]
    graph[no1].append([abs(city1[0][0] - city2[0][0]),no2])
    graph[no2].append([abs(city1[0][0] - city2[0][0]),no1])
cities.sort(key =lambda x:x[0][1])
for city1,city2 in zip(cities[0:-1],cities[1:]):
    no1 = city1[1]
    no2 = city2[1]
    graph[no1].append([abs(city1[0][1] - city2[0][1]),no2])
    graph[no2].append([abs(city1[0][1] - city2[0][1]),no1])


print(prime_method(graph))

Submission status: Time Limit Exceeded

Solution code:
class UnionFind(object):
    def __init__(self, size):
        self.parent = [i for i in range(size)]
        self.rank = [0 for _ in range(size)]


    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            return self.find(self.parent[x])


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

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

    def same(self, x, y):
        return self.find(x) == self.find(y)
def compute_mst_kruskal(N, edges):#N = 頂点数、edges 0-indexed
    edges = sorted(edges, key = lambda x:x[2])
    UF = UnionFind(N)
    cost = 0
    for edge in edges:
        x, y, w = edge
        if not UF.same(x, y):
            UF.unite(x, y)
            cost+=w
    return cost
N = int(input())
ixy = []
for i in range(N):
    x, y = map(int, input().split())
    ixy.append((i, x, y))
xy_x = sorted(ixy, key = lambda x:x[1])
xy_y = sorted(ixy, key = lambda x:x[2])
edges = []
for i in range(N-1):
    i1, x1, y1 = xy_x[i]
    i2, x2, y2 = xy_x[i+1]
    edges.append((i1, i2, x2-x1))
    i1, x1, y1 = xy_y[i]
    i2, x2, y2 = xy_y[i+1]
    edges.append((i1, i2, y2-y1))
ans = compute_mst_kruskal(N, edges)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
import sys
input = sys.stdin.readline

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        for i in range(2 * N - 2):
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
L1 = []
L2 = []
for i in range(N):
    x, y = list(map(int, input().split()))
    L1.append([x, y, i + 1])
    L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []

for i in range(N - 1):
    u = Lx[i][2]
    v = Lx[i + 1][2]
    w = min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u = Ly[i][2]
    v = Ly[i + 1][2]
    w = min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush
import sys
input = sys.stdin.readline

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        while self.Q:
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
L1 = []
L2 = []
for i in range(N):
    x, y = list(map(int, input().split()))
    L1.append([x, y, i + 1])
    L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []

for i in range(N - 1):
    u = Lx[i][2]
    v = Lx[i + 1][2]
    w = min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u = Ly[i][2]
    v = Ly[i + 1][2]
    w = min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        while self.Q:
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
L1 = []
L2 = []
for i in range(N):
    x, y = list(map(int, input().split()))
    L1.append([x, y, i + 1])
    L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []

for i in range(N - 1):
    u = Lx[i][2]
    v = Lx[i + 1][2]
    w = min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u = Ly[i][2]
    v = Ly[i + 1][2]
    w = min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        while self.Q:
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
Lx = []
Ly = []
for i in range(N):
    x, y = list(map(int, input().split()))
    Lx.append([x, y, i + 1])
    Ly.append([y, x, i + 1])
Lx.sort()
Ly.sort()
Q = []

for i in range(N - 1):
    u, v, w = Lx[i][2], Lx[i + 1][2] ,min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u, v, w = Ly[i][2], Ly[i + 1][2] ,min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush, heapify

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        while self.Q:
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
Lx = []
Ly = []
for i in range(N):
    x, y = list(map(int, input().split()))
    Lx.append([x, y, i + 1])
    Ly.append([y, x, i + 1])
Lx = sorted(Lx)
Ly = sorted(Ly)
Q = []

for i in range(N - 1):
    u, v, w = Lx[i][2], Lx[i + 1][2] ,min(Lx[i + 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    Q.append([w, u, v])
    u, v, w = Ly[i][2], Ly[i + 1][2] ,min(Ly[i + 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    Q.append([w, u, v])
Q = sorted(Q)
Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappop, heappush

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (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
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
               self.rank[x] += 1

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        while self.Q:
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
L1 = []
L2 = []
for i in range(N):
    x, y = list(map(int, input().split()))
    L1.append([x, y, i + 1])
    L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []

for i in range(N - 1):
    u, v, w = Lx[i][2], Lx[i + 1][2] ,min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u, v, w = Ly[i][2], Ly[i + 1][2] ,min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
def getn():
    return int(sys.stdin.readline())
def getnums():
    return list(map(int,(sys.stdin.readline().split())))

INF=10000000000
n = getn()
pos = []
edge = [[] for i in range(n)]
for i in range(n):
    x,y = getnums()
    pos.append([x,y,i])

pos.sort(key=lambda x:x[0])
for i,j in zip(pos, pos[1:]):
    x1,y1,i1 = i
    x2,y2,i2 = j
    cost = min(abs(x1-x2), abs(y1-y2))
    edge[i1].append([cost,i2])
    edge[i2].append([cost,i1])

pos.sort(key=lambda x:x[1])
for i,j in zip(pos, pos[1:]):
    x1,y1,i1 = i
    x2,y2,i2 = j
    cost = min(abs(x1-x2), abs(y1-y2))
    edge[i1].append([cost,i2])
    edge[i2].append([cost,i1])

def prim(start, n):
    ans = 0
    n_set = 1
    group = set([start])
    q = edge[start]
    heapq.heapify(q)
    while(q):
        next_e = heapq.heappop(q)
        if next_e[1] in group:
            pass
        else:
            ans += next_e[0]
            group.add(next_e[1])
            for ne in edge[next_e[1]]:
                heapq.heappush(q, ne)
            n_set += 1
            #print("union: ", next_e[1], group)
            #print(q)
        if n_set == n:
            return ans

ans  = prim(0, n)
print(ans)
#print(edge)

Submission status: Time Limit Exceeded

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)]
x_sort = [] #[Xi,Yi,点番号]
y_sort = [] #[Yi,Xi,点番号]
for i in range(n):
    X,Y = map(int,input().split())
    x_sort.append([X,Y,i])
    y_sort.append([Y,X,i])
x_sort.sort()
y_sort.sort()
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: Time Limit Exceeded

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 = [[0,0,0] for i in range(n)]
for i in range(n):
    X,Y = map(int,input().split())
    p[i] = [X,Y,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: Time Limit Exceeded

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)]
x_sort = [] #[Xi,Yi,点番号]
y_sort = [] #[Yi,Xi,点番号]
for i in range(n):
    X,Y = map(int,input().split())
    x_sort.append([X,Y,i])
    y_sort.append([Y,X,i])
x_sort.sort()
y_sort.sort()
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: Time Limit Exceeded

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:
        v = -1
        while len(edgelist) != 0:
            minedge = heapq.heappop(edgelist)
            if used[minedge[1]]:
                v = minedge[1]
                break
        if v == -1:
            break
        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)]
x_sort = [] #[Xi,Yi,点番号]
y_sort = [] #[Yi,Xi,点番号]
for i in range(n):
    X,Y = map(int,input().split())
    x_sort.append([X,Y,i])
    y_sort.append([Y,X,i])
x_sort.sort()
y_sort.sort()
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: Time Limit Exceeded

Solution code:
from copy import deepcopy
import heapq
N = int(input())
T = [None for i in range(N)]
for i in range(N):
    x, y = map(int, input().split())
    T[i] = (x, y, i)
Tx, Ty = deepcopy(T), deepcopy(T)
Tx.sort()
Ty.sort(key = lambda x:x[1])

Edge = [[] for i in range(N)]
for i in range(N-1):
    Edge[Tx[i][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i+1][2]))
    Edge[Tx[i+1][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i][2]))
    Edge[Ty[i][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i+1][2]))
    Edge[Ty[i+1][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i][2]))

Dist = [float("inf") for i in range(N)]
Vis = [False for i in range(N)]
Dist[0] = 0
Q = [(0, 0)]
heapq.heapify(Q)
Cost = 0
while Q:
    ncost, now = heapq.heappop(Q)
    if not Vis[now]:
        Vis[now] = True
        Cost += ncost
        for node in Edge[now]:
            if not Vis[node[1]]:
                if Dist[node[1]] > node[0]:
                    Dist[node[1]] = node[0]
                    heapq.heappush(Q, (node[0], node[1]))

print(Cost)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
import heapq
N = int(input())
T = [None for i in range(N)]
for i in range(N):
    x, y = map(int, input().split())
    T[i] = (x, y, i)
Tx, Ty = deepcopy(T), deepcopy(T)
Tx.sort()
Ty.sort(key = lambda x:x[1])

Edge = [[] for i in range(N)]
for i in range(N-1):
    Edge[Tx[i][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i+1][2]))
    Edge[Tx[i+1][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i][2]))
    Edge[Ty[i][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i+1][2]))
    Edge[Ty[i+1][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i][2]))

Dist = [float("inf") for i in range(N)]
Vis = [False for i in range(N)]
Dist[0] = 0
Q = [(0, 0, 0)]
heapq.heapify(Q)
Cost = 0
while Q:
    ndist, ncost, now = heapq.heappop(Q)
    if not Vis[now]:
        Vis[now] = True
        Cost += ncost
        for node in Edge[now]:
            if not Vis[node[1]]:
                if Dist[node[1]] >= ndist + node[0]:
                    Dist[node[1]] = ndist + node[0]
                    heapq.heappush(Q, (ndist + node[0], node[0], node[1]))

print(Cost)

Submission status: Time Limit Exceeded

Solution code:
from copy import deepcopy
import heapq
N = int(input())
T = []
for i in range(N):
    x, y = map(int, input().split())
    T.append((x, y, i))
Tx, Ty = deepcopy(T), deepcopy(T)
Tx.sort()
Ty.sort(key = lambda x:x[1])

Edge = [[] for i in range(N)]
for i in range(N-1):
    dx = min(abs(Tx[i][0]-Tx[i+1][0]), abs(Tx[i][1]-Tx[i+1][1]))
    dy = min(abs(Ty[i][0]-Ty[i+1][0]), abs(Ty[i][1]-Ty[i+1][1]))
    Edge[Tx[i][2]].append((dx, Tx[i+1][2]))
    Edge[Tx[i+1][2]].append((dx, Tx[i][2]))
    Edge[Ty[i][2]].append((dy, Ty[i+1][2]))
    Edge[Ty[i+1][2]].append((dy, Ty[i][2]))

Dist = [float("inf") for i in range(N)]
Vis = [False for i in range(N)]
Dist[0] = 0
Q = [(0, 0, 0)]
heapq.heapify(Q)
Cost = 0
while Q:
    ndist, ncost, now = heapq.heappop(Q)
    if not Vis[now]:
        Vis[now] = True
        Cost += ncost
        for node in Edge[now]:
            if not Vis[node[1]]:
                if Dist[node[1]] >= ndist + node[0]:
                    Dist[node[1]] = ndist + node[0]
                    heapq.heappush(Q, (ndist + node[0], node[0], node[1]))

print(Cost)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import sys
sys.setrecursionlimit(10 ** 7)

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

#	def find(self, x):
#		while self.table[x] >= 0:
#			x = self.table[x]
#		return x

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

			self.count += 1
			return True
		return False

n = int(input())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []
uf = UnionFind(n)

for i in range(n - 1):
	if vx[i][1] == vx[i + 1][1]:
		uf.union(vx[i][0], vx[i + 1][0])
	else:
		heapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))

	if vy[i][1] == vy[i + 1][1]:
		uf.union(vy[i][0], vy[i + 1][0])
	else:
		heapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))


#edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

ans = 0

while edges != []:
	e = heapq.heappop(edges)
	if uf.union(e[1], e[2]):
		ans += e[0]
	if uf.count == n - 1:
		break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

	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

			self.count += 1
			return True
		return False

n = int(input())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []
uf = UnionFind(n)

for i in range(n - 1):
	if vx[i][1] == vx[i + 1][1]:
		uf.union(vx[i][0], vx[i + 1][0])
	else:
		heapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))

	if vy[i][1] == vy[i + 1][1]:
		uf.union(vy[i][0], vy[i + 1][0])
	else:
		heapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))


#edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

ans = 0

while edges != []:
	e = heapq.heappop(edges)
	if uf.union(e[1], e[2]):
		ans += e[0]
	if uf.count == n - 1:
		break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

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

	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

			self.count += 1
		return

n = int(input())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []
uf = UnionFind(n)

for i in range(n - 1):
	if vx[i][1] == vx[i + 1][1]:
		uf.union(vx[i][0], vx[i + 1][0])
	else:
		heapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))

	if vy[i][1] == vy[i + 1][1]:
		uf.union(vy[i][0], vy[i + 1][0])
	else:
		heapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))


#edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

ans = 0

while edges != []:
	e = heapq.heappop(edges)
	if uf.find(e[1]) != uf.find(e[2]):
		uf.union(e[1], e[2])
		ans += e[0]
	if uf.count == n - 1:
		break

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq

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())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []
uf = UnionFind(n)

for i in range(n - 1):
	if vx[i][1] == vx[i + 1][1]:
		uf.union(vx[i][0], vx[i + 1][0])
	else:
		heapq.heappush(edges, (vx[i + 1][1] - vx[i][1], vx[i][0], vx[i + 1][0]))

	if vy[i][1] == vy[i + 1][1]:
		uf.union(vy[i][0], vy[i + 1][0])
	else:
		heapq.heappush(edges, (vy[i + 1][1] - vy[i][1], vy[i][0], vy[i + 1][0]))


#edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

ans = 0

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#心折れた

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())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []
uf = UnionFind(n)

for i in range(n - 1):
	if vx[i][1] == vx[i + 1][1]:
		uf.union(vx[i][0], vx[i + 1][0])
	else:
		edges.append([vx[i][0], vx[i + 1][0], vx[i + 1][1] - vx[i][1]])

	if vy[i][1] == vy[i + 1][1]:
		uf.union(vy[i][0], vy[i + 1][0])
	else:
		edges.append([vy[i][0], vy[i + 1][0], vy[i + 1][1] - vy[i][1]])

edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

ans = 0

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

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#心折れた

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())
x = []
y = []
for i in range(n):
	a, b = map(int, input().split())
	x.append([i, a])
	y.append([i, b])

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

edges = []

for i in range(n - 1):
	edges.append([vx[i][0], vx[i + 1][0], vx[i + 1][1] - vx[i][1]])
	edges.append([vy[i][0], vy[i + 1][0], vy[i + 1][1] - vy[i][1]])

edges = sorted(edges, key=lambda x: x[2], reverse=True)
#print(edges)

uf = UnionFind(n)

ans = 0

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

print(ans)