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: Accepted

Solution code:
# TEST

from math import sin, cos, tan, asin, acos, atan, sqrt, floor, ceil, pi, log10, log, gcd, hypot
from itertools import accumulate, permutations, combinations
from collections import deque, defaultdict, Counter
from bisect import bisect_left, bisect_right
from copy import deepcopy
from decimal import Decimal
import heapq
import sys
#import numpy as np
mod = 10**9 + 7
#mod =998244353


sys.setrecursionlimit(10**7)
input = sys.stdin.readline


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

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


class BIT():
    # 1,,,,,,,Nまでの数値を扱える
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)

    def to_sum(self, i):
        # i番目のところまでのΣ
        s = 0
        while i > 0:
            s += self.data[i]
            i -= (i & -i)
        return s

    def add(self, i, x):
        # i 番目のところに+
        while i <= self.n:
            self.data[i] += x
            i += (i & -i)

    def get(self, i, j):
        # i番目からj番目までの要素のΣ(1<=i<=j<=Nという制約)
        return self.to_sum(j)-self.to_sum(i-1)


class SegTree():
    # 1-indexed
    def __init__(self, lists, function, basement):
        self.n = len(lists)
        self.K = (self.n-1).bit_length()
        self.f = function
        self.b = basement
        self.seg = [basement]*(2**(self.K+1)+1)
        X = 2**self.K
        for i, v in enumerate(lists):
            self.seg[i+X] = v
        for i in range(X-1, 0, -1):
            self.seg[i] = self.f(self.seg[i << 1], self.seg[i << 1 | 1])

    def update(self, k, value):
        X = 2**self.K
        k += X
        self.seg[k] = value
        while k:
            k = k >> 1
            self.seg[k] = self.f(self.seg[k << 1], self.seg[(k << 1) | 1])

    def query(self, L, R):
        num = 2**self.K
        L += num
        R += num
        vL = self.b
        vR = self.b
        while L < R:
            if L & 1:
                vL = self.f(vL, self.seg[L])
                L += 1
            if R & 1:
                R -= 1
                vR = self.f(self.seg[R], vR)
            L >>= 1
            R >>= 1
        return self.f(vL, vR)

    def find_max_index(self, L, R, X):
        # [L,R)でX以下の物で最大indexを取得
        return self.fMi(L, R, X, 1, 0, 2**self.K)

    def find_min_index(self, L, R, X):
        # [L,R) でX以下の物で最小のindexを取得する
        return self.fmi(L, R, X, 1, 0, 2**self.K)

    def fMi(self, a, b, x, k, l, r):
        if self.seg[k] > x or r <= a or b <= l:
            # X以上のもの、の時は不等号をself.seg[k]<xにする
            return -1
        else:
            if k >= 2**self.K:
                return k-2**self.K
            else:
                vr = self.fMi(a, b, x, (k << 1) | 1, (l + r) // 2, r)
                if vr != -1:
                    return vr
                return self.fMi(a, b, x, k << 1, l, (l + r) // 2)

    def fmi(self, a, b, x, k, l, r):
        if self.seg[k] > x or r <= a or b <= l:
            # X以上のもの、の時は不等号をself.seg[k]<xにする
            return -1
        else:
            if k >= 2**self.K:
                return k-2**self.K
            else:
                vl = self.fmi(a, b, x, k << 1, l, (l+r)//2)
                if vl != -1:
                    return vl
                return self.fmi(a, b, x, k << 1 | 1, (l+r)//2, r)


class LCA():

    def _bfs(self, node):
        self.visited[node] = True
        for p in tree[node]:
            if self.visited[p] == False:
                self.kprv[0][p] = node
                self.depth[p] = self.depth[node]+1
                self._bfs(p)

    def __init__(self, root, tree):
        self.root = root
        self.n = len(tree)-1
        self.K = (self.n-1).bit_length()
        self.visited = [False for i in range(self.n+1)]
        self.depth = [0 for i in range(self.n+1)]
        self.kprv = [[-1 for i in range(self.n+1)] for j in range(self.K+1)]
        self._bfs(self.root)
        for cnt in range(1, self.K+1):
            for node in range(self.n+1):
                if self.kprv[cnt-1][node] >= 0:
                    self.kprv[cnt][node] = self.kprv[cnt -
                                                     1][self.kprv[cnt-1][node]]
                else:
                    self.kprv[cnt][node] = -1

    def query(self, u, v):
        # u,vの最小共通祖先

        dd = self.depth[v]-self.depth[u]

        if dd < 0:
            u, v = v, u
            dd = -dd

        for i in range(self.K+1):
            if dd & 1:
                v = self.kprv[i][v]
            dd >>= 1
        if u == v:
            return u

        for i in range(self.K-1, -1, -1):
            pu = self.kprv[i][u]
            pv = self.kprv[i][v]
            if pu != pv:
                u = pu
                v = pv
        return self.kprv[0][u]


class Combi():
    def __init__(self, N, mod):
        self.power = [1 for _ in range(N+1)]
        self.rev = [1 for _ in range(N+1)]
        self.mod = mod
        for i in range(2, N+1):
            self.power[i] = (self.power[i-1]*i) % self.mod
        self.rev[N] = pow(self.power[N], self.mod-2, self.mod)
        for j in range(N, 0, -1):
            self.rev[j-1] = (self.rev[j]*j) % self.mod

    def C(self, K, R):
        if K < R:
            return 0
        else:
            return ((self.power[K])*(self.rev[K-R])*(self.rev[R])) % self.mod

    def P(self, K, R):
        if K < R:
            return 0
        else:
            return (self.power[K])*(self.rev[K-R]) % self.mod


class Graph():
    def __init__(self, N, Type):
        self._V = N  # 頂点の数
        self._E = 0  # 辺の数
        self.type = Type
        if Type == "D":
            # 2次元リスト
            self.G = [[] for i in range(self._V+1)]
        elif Type == "W":
            # 隣接行列
            self.G = [[float("inf") for i in range(self._V+1)]
                      for j in range(self._V+1)]
        elif Type == "B" or Type == "K":
            # 1次元リスト
            self.G = []

    def E(self):
        """ 辺数 """
        return self._E

    @property
    def V(self):
        """ 頂点数 """
        return self._V

    def add(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する """
        self._E += 1
        if self.type == "D":
            self.G[_from].append((_to, _cost))

        elif self.type == "W":
            self.G[_from][_to] = _cost

        elif self.type == "B" or self.type == "K":
            self.G.append((_from, _to, _cost))

    def add_both(self, _from, _to, _cost):
        """ 2頂点と、辺のコストを追加する (無向グラフ) """
        self.add(_from, _to, _cost)
        self.add(_to, _from, _cost)


class Dijkstra(Graph):
    def __init__(self, N):
        super().__init__(N, "D")
        self.d = [10**20]*(self._V + 1)
        self.que = []
        heapq.heapify(self.que)

    def shortest_path(self, s):
        for i in range(self._V+1):
            self.d[i] = 10**20
        self.d[s] = 0
        heapq.heappush(self.que, (0, s))
        while self.que:
            cost, v = heapq.heappop(self.que)
            if self.d[v] < cost:
                continue

            for node, cost in self.G[v]:
                if self.d[node] > self.d[v] + cost:
                    self.d[node] = self.d[v] + cost
                    heapq.heappush(self.que, (self.d[node], node))
        return self.d


class Bellman_Ford(Graph):
    def __init__(self, N):
        super().__init__(N, "B")
        self.d = [10**20]*(self._V+1)

    def shortest_path(self, s):
        for i in range(self._V+1):
            self.d[i] = 10**20
        self.d[s] = 0
        for _ in range(self._V):
            flag = False
            for From, To, cost in self.G:
                newlen = self.d[From]+cost
                if newlen < self.d[To]:
                    flag = True
                    self.d[To] = newlen
            if not flag:
                break
        return self.d

    def have_negative_circle(self):
        for i in range(self._V+1):
            self.d[i] = 10**20
        self.d[1] = 0
        for i in range(1, self._V+1):
            flag = False
            for From, To, cost in self.G:
                newlen = self.d[From]+cost
                if newlen < self.d[To]:
                    flag = True
                    self.d[To] = newlen
            if not flag:
                break
            if i == self._V:
                return True
        return False


class Warshall_Floyd(Graph):

    def __init__(self, N):
        super().__init__(N, "W")

    def shortest_path(self):
        # 破壊的メソッド
        _N = self._V
        for i in range(_N+1):
            self.G[i][i] = 0
        for k in range(1, _N+1):
            for i in range(1, _N+1):
                for j in range(1, _N+1):
                    self.G[i][j] = min(self.G[i][j], self.G[i][k]+self.G[k][j])
        return self.G


class Kruskal(Graph):
    def __init__(self, N):
        super().__init__(N, "K")
        self.connected_G = UnionFind(self._V)

    def find_lowest_cost(self):
        res = 0
        self.G.sort(lambda x:x[-1])
        for p, q, cost in self.G:
            if not self.connected_G.same(p, q):
                self.connected_G.union(p, q)
                res += cost
        return res


def union_lcm(lists):
    if len(lists) == 1:
        return lists[0]
    elif len(lists) > 1:
        num = lists[0]
        for i in range(1, len(lists)):
            num = num*lists[i]//gcd(num, lists[i])
        return num


def union_gcd(lists):
    if len(lists) == 1:
        return lists[0]
    elif len(lists) > 1:
        num = lists[0]
        for i in range(1, len(lists)):
            num = gcd(num, lists[i])
        return num


def is_prime(N):
    for i in range(2, N+1):
        if i**2 > N:
            break
        if N % i == 0:
            return False
    return True


class Primes():
    def __init__(self, N):
        self.N = N
        self.prime = {i for i in range(2, self.N+1)}
        for i in range(2, self.N+1):
            if i in self.prime:
                for j in range(i*2, self.N+1, i):
                    if j in self.prime:
                        self.prime.remove(j)

    def show_primes(self):
        return self.prime

    def is_prime(self, X):
        if X < self.N:
            return X in self.prime
        else:
            return "Unknown"


def main():
    # start coding here...
    N = int(input())
    d = []

    for i in range(N):
        x, y = map(int, input().split())
        d.append((i+1, x, y))

    G = Kruskal(N)

    d.sort(key=lambda x: x[1])

    for i in range(N-1):
        a, px, py = d[i]
        b, qx, qy = d[i+1]
        dis = abs(px-qx)
        G.add_both(a, b ,dis)

    d.sort(key=lambda x: x[2])

    for i in range(N-1):
        a, px, py = d[i]
        b, qx, qy = d[i+1]
        dis = abs(py-qy)
        G.add_both(a, b, dis)

    print(G.find_lowest_cost())


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
class UnionFind():
    # 初めは全ての頂点が別々の木の根
    def __init__(self, n):  # n要素で初期化
        self.parent = list(range(n)) # 親
        self.rank = [0] * n   # 木の深さ

    def root_of(self, x):
        children = [x]
        while self.parent[x] != x:
            x = self.parent[x]
            children.append(x)

        for ch in children:
            self.parent[ch] = x
        return x

    # xとyの属する集合を併合
    def union(self, x, y):
        rx = self.root_of(x)
        ry = self.root_of(y)
        if rx == ry:
            return
        if self.rank[rx] < self.rank[ry]: # ランクの小さい木から大きい木の根に辺を張る
            self.parent[rx] = ry  # rxをryの子とする
        else:
            self.parent[ry] = rx
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    # 同じ集合に属するかどうか
    def same(self, x, y):
        return self.root_of(x) == self.root_of(y)


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

X.sort()
Y.sort()
E = []
xp = X[0][0]
ip = X[0][1]
for (x, i) in X:
    E.append((x - xp, (ip, i)))
    xp = x
    ip = i

yp = Y[0][0]
ip = Y[0][1]
for (y, i) in Y:
    E.append((y - yp, (ip, i)))
    yp = y
    ip = i

E.sort()
uf = UnionFind(N)
cost = 0
for c, (e1, e2) in E:
    if uf.same(e1, e2): continue
    cost += c
    uf.union(e1, e2)

print(cost)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
finput=lambda:sys.stdin.readline().strip()

class Unionfind():
    def __init__(self,n):
        self.parents=[-1]*n
        self.ranks=[0]*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.ranks[x]<self.ranks[y]:
            x,y=y,x
        self.parents[x]+=self.parents[y]
        self.parents[y]=x
        if self.ranks[x]==self.ranks[y]:
            self.ranks[x]+=1
    
    def size(self,x):
        return -self.parents[self.find(x)]
    
    def issametree(self,x,y):
        return self.find(x)==self.find(y)

def main():
    n=int(finput())
    coor=[list(map(int,finput().split()))+[i] for i in range(n)]
    coor.sort(key=lambda e:e[0])
    cost = lambda e,f:min(abs(e[0]-f[0]),abs(e[1]-f[1]))
    ew=dict(((coor[i][2],coor[i+1][2]),cost(coor[i][:2],coor[i+1][:2])) for i in range(n-1))
    coor.sort(key=lambda e:e[1])
    ew.update(dict(((coor[i][2],coor[i+1][2]),cost(coor[i][:2],coor[i+1][:2])) for i in range(n-1)))
    edges=sorted(list(iter(ew)),key=lambda e:ew[e])
    v=Unionfind(n)
    totcost=0
    # print(ew)
    # print(edges)
    for edge in edges:
        if not v.issametree(edge[0],edge[1]):
            v.union(edge[0],edge[1])
            totcost+=ew[edge]
    print(totcost)
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import heapq

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())
xy = [list(map(int, input().split()))+[i] for i in range(n)]
"""
辺を結びたいがすべての点で結ぶと膨大になる
"""

edge = []
xy.sort()
for i, j in zip(range(n-1), range(1, n)):
    cost = xy[j][0] - xy[i][0]
    heapq.heappush(edge, [cost, xy[i][2], xy[j][2]])

xy.sort(key= lambda x: x[1])
for i, j in zip(range(n-1), range(1, n)):
    cost = xy[j][1] - xy[i][1]
    heapq.heappush(edge, [cost, xy[i][2], xy[j][2]])

uf = UnionFind(n)
ans = 0
while edge:
    c, a, b = heapq.heappop(edge)
    if uf.same(a, b): continue
    uf.union(a, b)
    ans += c

print(ans)

Submission status: Accepted

Solution code:
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())
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=[]
for i in range(n-1):
    E.append([X[i+1][0]-X[i][0],X[i][1],X[i+1][1]])
    E.append([Y[i+1][0]-Y[i][0],Y[i][1],Y[i+1][1]])
E.sort()
U=UnionFind(n)
ans=0
for i in range(2*n-2):
    d=E[i][0]
    j1=E[i][1]
    j2=E[i][2]
    if not U.same(j1,j2):
        ans+=d
        U.union(j1,j2)
print(ans)

Submission status: Accepted

Solution code:
import sys
buf = sys.stdin.buffer

class UnionFind:
  def __init__(self, num_of_node):
    self.roots = [-1] * num_of_node
    self.ranks = [1] * num_of_node
    self.groups = num_of_node
 
  def get_root(self, node):
    root = self.roots[node]
    if root == -1:
      return node
    else:
      root = self.get_root(root)
      self.roots[node] = root
      return root

  def is_same_group(self, node1, node2):
    return self.get_root(node1) == self.get_root(node2)

  def unite(self, node1, node2):
    self.groups -= 1
    root1, root2 = self.get_root(node1), self.get_root(node2)
    rank1, rank2 = self.ranks[root1], self.ranks[root2]
    if rank1 < rank2:
      root1, root2 = root2, root1
    self.roots[root2] = root1
    self.ranks[root2] += self.ranks[root1]

def main():
  n = int(buf.readline())
  XY = map(int, buf.read().split())
  Xs = []
  Ys = []
  for i, (x, y) in enumerate(zip(XY, XY)):
    Xs.append((x-1, i))
    Ys.append((y-1, i))
    
  Xs.sort()
  Ys.sort()
  
  edges = []
  for i, ((x, node), (nx, new_node)) in enumerate(zip(Xs[:-1], Xs[1:])):
    edges.append((nx-x, node, new_node))
 
  for i, ((y, node), (ny, new_node)) in enumerate(zip(Ys[:-1], Ys[1:])):
    edges.append((ny-y, node, new_node))
 
  edges.sort(reverse=True)
 
  ans = 0
  uf = UnionFind(n)
  while uf.groups != 1:
    d, node1, node2 = edges.pop()
    if uf.is_same_group(node1, node2):
      continue
    uf.unite(node1, node2)
    ans += d
  print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc065/tasks/arc076_b
import copy


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

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

    def union(self, x, y):
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return False
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        return True


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

# (start, end, cost)
edges = []

# x座標でソートしてx座標が隣り合う点にをedge候補に
rows_x = copy.deepcopy(rows)
rows_x.sort(key=lambda x: x[1])
for i in range(len(rows)-1):
    left = rows_x[i]
    right = rows_x[i+1]
    edges.append((left[0], right[0], right[1] - left[1]))

# print(rows)
rows_y = copy.deepcopy(rows)
rows_y.sort(key=lambda x: x[2])
for i in range(len(rows)-1):
    down = rows_y[i]
    up = rows_y[i+1]
    edges.append((down[0], up[0], up[2] - down[2]))

# print(edges)

uf = UnionFind(n)

edges.sort(key=lambda edge: edge[2])

result = 0
for edge in edges:
    s, t, c = edge
    unioned = uf.union(s, t)
    if unioned:
        result += c

print(result)

Submission status: Accepted

Solution code:
ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

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

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

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if(x == y):
            return False
        if(self.d[x] > self.d[y]):
            x, y = y, x
        self.d[x] += self.d[y]
        self.d[y] = x
        return True

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

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

n = ii()

uf = UnionFind(n)
path = [] # d,s,t

xaxis = []
yaxis = []

ans = 0
cnt = 0

for i in range(n):
    x,y = mi()
    xaxis.append([x, i])
    yaxis.append([y, i])

xaxis.sort()
yaxis.sort()

for k,i in enumerate(xaxis[1:]):
    d = i[0] - xaxis[k][0] 
    s = xaxis[k][1]
    t = i[1]
    if d != 0:
        path.append([d,s,t])
    else:
        if uf.same(s, t) == False:
            uf.union(s,t)
            cnt += 1

for k,i in enumerate(yaxis[1:]):
    d = i[0] - yaxis[k][0] 
    s = yaxis[k][1]
    t = i[1]
    if d != 0:
        path.append([d,s,t])
    else:
        if uf.same(s, t) == False:
            uf.union(s,t)
            cnt += 1

path.sort()

for i in path:
    if cnt == n-1:
        break
    d = i[0]
    s = i[1]
    t = i[2]
    if uf.same(s,t) == False:
        uf.union(s,t)
        cnt += 1
        ans += d

print(ans)

Submission status: Accepted

Solution code:
N = int(input())

def find(x, U, r):
  p = []
  while not x == U[x]:
    p.append(x)
    x = U[x]
  for x_ in p:
    U[x_] == x
  return x
  
def merge(x, y, U, r):
  x = find(x, U, r)
  y = find(y, U, r)
  
  if x == y:
    return False
  #print(x,y, U)
  if r[x] < r[y]:
    x, y = y, x
  U[y] = x
  r[x] = max(r[y]+1, r[x])
  #print(x,y, U)
  return True
  
U = [i for i in range(N)]
r = [0 for _ in range(N)]

B = []
C = []
for i in range(N):
  u, v = map(int, input().split())
  B.append((u, v, i))
  C.append((v, u, i))
B.sort()
C.sort()

#辺の作成
R = []
for i in range(1,N):
  c = B[i][0] - B[i-1][0]
  p1 = B[i][2]
  p2 = B[i-1][2]
  R.append((c, p1, p2))
  
  c = C[i][0] - C[i-1][0]
  p1 = C[i][2]
  p2 = C[i-1][2]
  R.append((c, p1, p2))
R.sort()

#Union Find:
U = [i for i in range(N)]
r = [0 for _ in range(N)]
#print(U)  
ans = 0
for road in R:
  c = road[0]
  x = road[1]
  y = road[2]
  if merge(x, y, U, r):
    #print(U)  
    ans += c
#print(U)    
print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
xy1 = [None]*n
for i in range(n):
    x,y = tuple(map(int, input().split()))
    xy1[i] = (x,y,i)
xy2 = xy1[:]
xy1.sort()
xy2.sort(key=lambda x: x[1])

from collections import defaultdict
ns = defaultdict(set)
for i in range(n):
    x1,y1,i1 = xy1[i]
    x2,y2,i2 = xy2[i]
    if i>0:
        ns[i1].add((abs(x1-xy1[i-1][0]), xy1[i-1][2]))
        ns[i2].add((abs(y2-xy2[i-1][1]), xy2[i-1][2]))
    if i<n-1:
        ns[i1].add((abs(x1-xy1[i+1][0]), xy1[i+1][2]))
        ns[i2].add((abs(y2-xy2[i+1][1]), xy2[i+1][2]))
from collections import defaultdict
from heapq import heappush as hpush, heappop as hpop

def prim(ns):
    # n頂点の木, 隣接リストnsに対するプリム法
    seen = [False] * n
    seen[0] = True
    q = []
    for d,u in ns[0]:
        hpush(q, (d,u))
    val = 0
    for _ in range(n-1):
        while True:
            d,u = hpop(q)
            if not seen[u]:
                val += d
                seen[u] = True
                for d,v in ns[u]:
                    if not seen[v]:
                        hpush(q, (d,v))
                break
    return val
val = prim(ns)
print(val)

Submission status: Accepted

Solution code:
n = int(input())
x,y = [],[]
for i in range(n):
    a,b = map(int,input().split())
    x.append([a,i])
    y.append([b,i])
x.sort()
y.sort()
g = [[] for _ in range(n)]
for i in range(n-1):
    g[x[i][1]].append([abs(x[i+1][0]-x[i][0]),x[i+1][1]])
    g[x[i+1][1]].append([abs(x[i+1][0]-x[i][0]),x[i][1]])
    g[y[i][1]].append([abs(y[i+1][0]-y[i][0]),y[i+1][1]])
    g[y[i+1][1]].append([abs(y[i+1][0]-y[i][0]),y[i][1]])
import heapq
hq = []
for d,e in g[0]:
    heapq.heappush(hq,[d,e])
cnt = 1
visit = [False]*n
visit[0] = True
ans = 0
while cnt <n:
    cost, end = heapq.heappop(hq)
    if visit[end]: continue
    ans += cost
    visit[end] = True
    cnt += 1
    for d,e in g[end]:
        if not visit[e]:
            heapq.heappush(hq,[d,e])
print(ans)

Submission status: Accepted

Solution code:
#Union Find
class union_find:
    #初期化
    #根なら-size,子なら親の頂点
    # par = [-1]*N
    def __init__(self, N):
        self.par = [-1]*N

    #xの根を求める
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    #xとyの属する集合の併合
    def unite(self, x,y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return False
        else:
            #sizeの大きいほうがx
            if self.par[x] > self.par[y]:
                x,y = y,x
            self.par[x] += self.par[y]
            self.par[y] = x
            return True

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

    #xが属する集合の個数
    def size(self, x):
        return -self.par[self.find(x)]

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

import heapq
edges = []
heapq.heapify(edges)

XYI.sort(key=lambda x: x[0])
for j in range(1, N):
    px, py, pi = XYI[j-1]
    x, y, i = XYI[j]
    d = min(abs(x-px), abs(y-py))
    heapq.heappush(edges, (d, pi, i))

XYI.sort(key=lambda x: x[1])
for j in range(1, N):
    px, py, pi = XYI[j-1]
    x, y, i = XYI[j]
    d = min(abs(x-px), abs(y-py))
    heapq.heappush(edges, (d, pi, i))

uf = union_find(N)
ans = 0
while True:
    d, i, j = heapq.heappop(edges)
    if uf.same(i, j): continue
    uf.unite(i, j)
    ans += d
    if uf.size(i) == N: break

print(ans)

Submission status: Accepted

Solution code:
import queue

N = int(input())

pos = []
for _ in range(N):
    a, b = map(int, input().split())
    pos.append((a, b))

visited = {v: False for v in pos}
edges = {v: [] for v in pos}
x_sorted = sorted([(p[0], i) for i, p in enumerate(pos)])
for i in range(len(x_sorted) - 1):
    j = x_sorted[i][1]
    l = x_sorted[i+1][1]
    edges[pos[j]].append((pos[l], abs(pos[l][0] - pos[j][0])))
    edges[pos[l]].append((pos[j], abs(pos[l][0] - pos[j][0])))
y_sorted = sorted([(p[1], i) for i, p in enumerate(pos)])
for i in range(len(y_sorted) - 1):
    j = y_sorted[i][1]
    l = y_sorted[i+1][1]
    edges[pos[j]].append((pos[l], abs(pos[l][1] - pos[j][1])))
    edges[pos[l]].append((pos[j], abs(pos[l][1] - pos[j][1])))

que = queue.PriorityQueue()
que.put((0, pos[0]))

res = 0
while not que.empty():
    cost, vertex = que.get()
    if visited[vertex]:
        continue
    visited[vertex] = True
    res += cost

    for to, next_cost in edges[vertex]:
        if not visited[to]:
            que.put((next_cost, to))

print(res)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7

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):
        """
        yをxの根に繋ぐ
        """
        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):
        """
        xとyが同じ連結成分か判別する
        """
        return self.find(x) == self.find(y)

    def size(self, x):
        """
        xの連結成分の大きさを返す
        """
        return -self.parents[self.find(x)]

    def kruskal(self, edge):
        """
        :param edge: edge = [(コスト, 頂点1, 頂点2),...]の形で重み付き隣接リストを渡して下さい
        :return: 最小全域木のコストの和
        """
        edge.sort()
        cost_sum = 0
        for cost, node1, node2 in edge:
            if not self.same(node1, node2):
                cost_sum += cost
                self.union(node1, node2)
        return cost_sum


def resolve():
    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):
        cost1 = X[i][0] - X[i - 1][0]
        edge.append([cost1, X[i - 1][1], X[i][1]])
        cost2 = Y[i][0] - Y[i - 1][0]
        edge.append([cost2, Y[i - 1][1], Y[i][1]])

    uf = UnionFind(n)
    res = uf.kruskal(edge)
    print(res)


if __name__ == '__main__':
    resolve()