Harryxun/testdata huggingface dataset:
Buggy python submission (verdict: Runtime Error):
N = int(input())
num = (N-2)**(0.5)
if N == 3:
  print("Yes");print(3)
  A = [2, 1, 2]; print(*A)
  A = [2, 2, 3]; print(*A)
  A = [2, 3, 1]; print(*A); exit()
if num%1 != 0:
  print("No");exit()
num = int(num)
ans = []
for i in range(num):
  temp = [1] + [2+j+num*i for j in range(num)]
  ans.append(temp)
for i in range(num):
  temp = [2+i+num*j for j in range(num)] + [N]
  ans.append(temp)
print("Yes")
print(num*2)
for x in ans:
  ret = [num+1] + x
  print(*ret)

Fixed submission:
N = int(input())
MAX = 450
A = [[1],[1]] #size = 2
#A = [[1,2],[2,3],[3.1]]
size = 0
for i in range(1,MAX):
  if i*(i+1)//2 == N:
    size = i+1
    break
if size == 0:
  print("No")
  exit()
now = 2
while now < size:
  start = now*(now-1)//2+1
  last = [start+i for i in range(now)]
  for j in range(len(A)):
    A[j].append(last[j])
  A.append(last)
  now += 1
print("Yes")
print(len(A))
#ini = [len(A)-1]
for x in A:
  x.insert(0,len(A)-1)
  print(*x)

Buggy python submission (verdict: Runtime Error):
N = int(input())
num = (N-2)**(0.5)
if N == 3:
  print("Yes")
  A = [2, 1, 2]; print(*A)
  A = [2, 2, 3]; print(*A)
  A = [2, 3, 1]; print(*A); exit()
if num%1 != 0:
  print("No");exit()
num = int(num)
ans = []
for i in range(num):
  temp = [1] + [2+j+num*i for j in range(num)]
  ans.append(temp)
for i in range(num):
  temp = [2+i+num*j for j in range(num)] + [N]
  ans.append(temp)
print("Yes")
for x in ans:
  ret = [num+1] + x
  print(*ret)

Fixed submission:
N = int(input())
MAX = 450
A = [[1],[1]] #size = 2
#A = [[1,2],[2,3],[3.1]]
size = 0
for i in range(1,MAX):
  if i*(i+1)//2 == N:
    size = i+1
    break
if size == 0:
  print("No")
  exit()
now = 2
while now < size:
  start = now*(now-1)//2+1
  last = [start+i for i in range(now)]
  for j in range(len(A)):
    A[j].append(last[j])
  A.append(last)
  now += 1
print("Yes")
print(len(A))
#ini = [len(A)-1]
for x in A:
  x.insert(0,len(A)-1)
  print(*x)
Buggy python submission (verdict: Runtime Error):
N, M = map(int,input().split())

s = M//N
for i in range(1,s):
  if M%i == 0:
    ans = i
print(ans)

Fixed submission:
N, M = map(int,input().split())

s = M//N
for i in reversed(range(1,s+1)):
  if M%i == 0:
    ans = i
    break
print(ans)
Buggy python submission (verdict: Time Limit Exceeded):
from collections import defaultdict
ODD = defaultdict(int)
EVEN = defaultdict(int)
ALL = set([])
N = int(input())

A = list(map(int,input().split()))
for i in range(N):
  ALL.add(A[i])
  if i%2 == 0:
    EVEN[A[i]] += 1
  else:
    ODD[A[i]] += 1
if len(ALL) == 1:
  ans = N//2
  print(ans)
  exit()
modd = max(ODD.values())
meven = max(EVEN.values())
mlodd = [];mleven = []
dicodd = sorted(ODD.items(), key=lambda x:x[1], reverse = True)
diceven = sorted(EVEN.items(), key=lambda x:x[1], reverse = True)
ans = N
for x, vx in dicodd:
  for y, vy in diceven:
    if x != y:
      temp = N-(vx+vy)
      if ans != temp:
        ans = min(ans,temp)
      else:
        print(ans)
        exit()
print(ans)
exit()
print(ans)


Fixed submission:
from collections import defaultdict
ODD = defaultdict(int)
EVEN = defaultdict(int)
ALL = set([])
N = int(input())

A = list(map(int,input().split()))
for i in range(N):
  ALL.add(A[i])
  if i%2 == 0:
    EVEN[A[i]] += 1
  else:
    ODD[A[i]] += 1
if len(ALL) == 1:
  ans = N//2
  print(ans)
  exit()
modd = max(ODD.values())
meven = max(EVEN.values())
mlodd = [];mleven = []
dicodd = sorted(ODD.items(), key=lambda x:x[1], reverse = True)
diceven = sorted(EVEN.items(), key=lambda x:x[1], reverse = True)
ans = N
if len(dicodd) > 1:
  X = [dicodd[0],dicodd[1]]
else:
  X = [dicodd[0]]
if len(diceven) > 1:
  Y = [diceven[0],diceven[1]]
else:
  Y = [diceven[0]]
#print(X)
#print(Y)
for x,v in X:
  for y,w in Y:
    if x == y:
      continue
    temp = N-(v+w)
    ans = min(ans,temp)

print(ans)
Buggy python submission (verdict: Runtime Error):
D,G = map(int,input().split())

P = []
C = []
for i in range(D):
  tempP, tempc = map(int, input().split())
  P.append(tempP)
  C.append(tempC)

print(P,C)


Fixed submission:
d, g = map(int, input().split())
pc = [list(map(int, input().split())) for i in range(d)]

ans = float("inf")

for bit in range(1 << d): #d個左にシフトする。d=2なら100となって十進法なら4。
    count = 0
    sum = 0
    nokori = [i+1 for i in range(d)]

    for i in range(d): #与えられbitにおいてすべて足し算する。
        if bit & (1 << i):
            sum += pc[i][0] * (i + 1) * 100 + pc[i][1]
            count += pc[i][0]
            nokori.remove(i + 1)

    # G 点に満たなければ nokori のうち一番大きいものを解く
    if sum < g:
        use = max(nokori)
        n = min(pc[use - 1][0], -(-(g - sum) // (use * 100)))
        count += n
        sum += n * use * 100

    if sum >= g:
        ans = min(ans, count)

print(ans)
Buggy python submission (verdict: Runtime Error):
N,M = map(int,input().split()))

if N<=8 and M<= 8:
  print("Yay!")
else:
  print(":(")

Fixed submission:
N,M = map(int,input().split())

if N<=8 and M<= 8:
  print("Yay!")
else:
  print(":(")
Buggy python submission (verdict: Runtime Error):
S = str(input())
N = len(S)
L = list(S)
L = set(L)
if N != 26: #含まないものがある
  for i in range(26):
    temp = chr(i+97)
    if temp not in L:
      ans = S+temp
      print(ans)
      exit()
M = []
for i in range(25):
  now = 25-i
  if S[now] > S[now-1]:
    ans = S[:now-1]+min(M)
    print(ans)
    exit()
  M.append(S[now])
print(-1)  

Fixed submission:
S = str(input())
N = len(S)
L = list(S)
L = set(L)
if N != 26: #含まないものがある
  for i in range(26):
    temp = chr(i+97)
    if temp not in L:
      ans = S+temp
      print(ans)
      exit()
M = []
All = [chr(97+i) for i in range(26)]
#print(All)
for i in range(25):
  now = 25-i
  M.append(S[now])
  if S[now] > S[now-1]:
    M.sort()
    for x in M:
      if x > S[now-1]:
        temp = x
        ans = S[:now-1]+temp
        print(ans)
        exit()
  
print(-1)
Buggy python submission (verdict: Runtime Error):
N,A,B = map(int,input().split())

if A+B > N+1:
  print("-1")
  exit()
if A == 1:
  if B== N:
    ans = [i+1 for i in reversed(range(N))]
    print(*ans)
    exit()
  else:
    print("-1")
    exit()
if B == 1:
  if A== N:
    ans = [i+1 for i in range(N)]
    print(*ans)
    exit()
  else:
    print("-1")
    exit()
if A >= B:
  Flag = True
else:
  Flag = False
  A,B = B,A
if (N+A-1)//A > B:
  print("-1")
  exit()
else:
  L = [[] for _ in range(B)]
  for i in range(B):
    temp = ""
    for j in range(A):
      if j+1+i*A <= N:
        temp += str(j+1+i*A)
        L[-i-1] = "".join(temp)
  ans = "".join(L)
  if Flag:
    s = " ".join([n for n in ans])
    print(s)
  else:
    t = reversed(list(ans))
    ans = " ".join(t)
    print(ans)
  exit()

Fixed submission:
import numpy as np
N,A,B = map(int,input().split())

if A+B > N+1:
  print("-1")
  exit()
if A == 1:
  if B== N:
    ans = [i+1 for i in reversed(range(N))]
    print(*ans)
    exit()
  else:
    print("-1")
    exit()
if B == 1:
  if A== N:
    ans = [i+1 for i in range(N)]
    print(*ans)
    exit()
  else:
    print("-1")
    exit()
if A >= B:
  Flag = True
else:
  Flag = False
  A,B = B,A
#print((N+A-1)//A, B)
if A*B<N:
  print("-1")
  exit()
else:
  L = [1 for _ in range(B)]
  nokori = N-B
  for i in range(B):
    if A-L[i] >0:
      temp = min(A-L[i],nokori)
      L[i] += temp
      nokori -= temp
    if nokori == 0:
      break
  now = 0
  P = [[] for _ in range(B)]
  for i,num in enumerate(L):
    for j in range(num):
      now += 1
      P[-i-1].append(now)
  #print(P)
  ans = P
  output = []
  for i in range(len(ans)):
    for j in ans[i]:
      output.append(j)
  if Flag:
    print(*output)
  else:
    output = output[::-1]
    print(*output)
Buggy python submission (verdict: Runtime Error):
H,W,D = map(int,input().split())
MAX = H*W
M = MAX//D+1
dic = {}

for i in range(H):
  temp = list(map(int,input().split()))
  for j in range(W):
    now = temp[j]
    dic[now] = (i,j)
#print(dic)
L = [[0] for _ in range(M)]
for i in range(D): #MODで0からD-1をひたすら見ていく。
  if i == 0:
    now = D
  else:
    now = i
  while now+D <= MAX:
    tsugi = now+D
    np = dic[now] #今の場所
    tp = dic[tsugi]
    dis = abs(np[0]-tp[0])+abs(np[1]-tp[1])
    L[i].append(L[i][-1]+dis)
    now = tsugi
#print(L,L[0])
Q = int(input())
for i in range(Q):
  left,right = map(int,input().split())
  MOD = left%D
  #print(L[MOD])
  start = (left-1)//D
  end = (right-1)//D
  ans = L[MOD][end]-L[MOD][start]
  print(ans)
    
  

Fixed submission:
H,W,D = map(int,input().split())
MAX = H*W
#M = MAX//D+1
dic = {}

for i in range(H):
  temp = list(map(int,input().split()))
  for j in range(W):
    now = temp[j]
    dic[now] = (i,j)
#print(dic)
L = [[0] for _ in range(D)]
for i in range(D): #MODで0からD-1をひたすら見ていく。
  if i == 0:
    now = D
  else:
    now = i
  while now+D <= MAX:
    tsugi = now+D
    np = dic[now] #今の場所
    tp = dic[tsugi]
    dis = abs(np[0]-tp[0])+abs(np[1]-tp[1])
    L[i].append(L[i][-1]+dis)
    now = tsugi
#print(L)
Q = int(input())
for i in range(Q):
  left,right = map(int,input().split())
  MOD = left%D
  #print(L[MOD])
  start = (left-1)//D
  end = (right-1)//D
  ans = L[MOD][end]-L[MOD][start]
  print(ans)
Buggy python submission (verdict: Runtime Error):
N = int(input())
MAX=11000
S = [_+2 for _ in range(MAX)]
old = S
i = 0
while True:
  new = set([])
  t = old[i]
  for j in range(len(old)):
    if old[j] == t or old[j]%t != 0:
      new.add(old[j])
  if len(old) == len(new):
    break
  old = list(new)
  old.sort()
  i += 1


#print(old)
A = [0 for _ in range(MAX)]  
for i in range(MAX):
  if i%2 == 0:
    continue
  if i in new and (i+1)//2 in new:
    A[i] = 1
SUM = [0 for _ in range(MAX)] 
for i in range(1,MAX):
  SUM[i] += A[i]+SUM[i-1]
#print(SUM)

for i in range(N):
  l,r = map(int,input().split())
  ans = SUM[r]-SUM[l-1]
  print(ans)

Fixed submission:
N = int(input())
MAX=110000
S = [_+2 for _ in range(MAX)]
old = S
i = 0
while True:
  new = set([])
  t = old[i]
  for j in range(len(old)):
    if old[j] == t or old[j]%t != 0:
      new.add(old[j])
  if len(old) == len(new):
    break
  old = list(new)
  old.sort()
  i += 1


#print(old)
A = [0 for _ in range(MAX)]  
for i in range(MAX):
  if i%2 == 0:
    continue
  if i in new and (i+1)//2 in new:
    A[i] = 1
SUM = [0 for _ in range(MAX)] 
for i in range(1,MAX):
  SUM[i] += A[i]+SUM[i-1]
#print(SUM)

for i in range(N):
  l,r = map(int,input().split())
  ans = SUM[r]-SUM[l-1]
  print(ans)
Buggy python submission (verdict: Runtime Error):
s = str(input()); n = len(s)
gx,gy = map(int,input().split())
Yoko = []; Tate = []
Flag = 0; cnt = 0
Max_x = 0; Max_y = 0
for i in range(n):
  if s[i] == "F":
    cnt += 1
    if i == n-1: #最後なら登録
      if Flag == 0:
        Max_x += cnt
        Yoko.append(cnt)
      else:
        Max_y += cnt
        Tate.append(cnt)      
  else: #T
    if Flag == 0:
      Max_x += cnt
      Yoko.append(cnt)
    else:
      Max_y = cnt
      Tate.append(cnt)
    cnt = 0
    Flag = Flag^1
#print(Yoko,Tate)
MAX_dpx = Max_x*2+1
dp = [0 for _ in range(MAX_dpx)]
dp[Max_x] = 1

for i,x in enumerate(Yoko):
  p = [0 for _ in range(MAX_dpx)]
  p,dp = dp,p
  for j in range(MAX_dpx):
    if i == 0: #i=0の時は右向きだけ
      if 0<=j+x<MAX_dpx:
        dp[j+x] = max(dp[j+x], p[j])
    else:
      if 0<=j+x<MAX_dpx:
        dp[j+x] = max(dp[j+x], p[j])
      if 0<=j-x<MAX_dpx:
        dp[j-x] = max(dp[j-x], p[j])
  #print(dp)
#print(dp)
#print(gx+Max_x,MAX_dpx)
if gx+Max_x >= MAX_dpx or dp[gx+Max_x] == 0:
  print("No");exit()

MAX_dpy = Max_y*2+1
dp = [0 for _ in range(MAX_dpy)]
dp[Max_y] = 1

for i,y in enumerate(Tate):
  p = [0 for _ in range(MAX_dpy)]
  p,dp = dp,p
  for j in range(MAX_dpy):
    if 0<=j+y<MAX_dpy:
       dp[j+y] = max(dp[j+y], p[j])
    if 0<=j-y<MAX_dpy:
      dp[j-y] = max(dp[j-y], p[j])
  #print(dp)
#print(dp)
if gy+Max_y >= MAX_dpy or dp[gy+Max_y] == 0:
  print("No")
else:
  print("Yes")

Fixed submission:
S = str(input())
N = len(S)
x,y = map(int,input().split())
X = []; Y =[]
Flag = True #Trueならx軸、Falseならy軸
seq = 0
for i in range(N):
  if S[i] == "T":
    if Flag:
      X.append(seq)
    if not Flag:
      Y.append(seq)
    Flag = not Flag
    seq = 0
  else:
    seq += 1
    if i == N-1:
      if Flag:
        X.append(seq)
      if not Flag:
        Y.append(seq)
#print(X,Y)
num = 8100 #真ん中
MAX = num*2+1
#X方向i回目でjにいる
dpx = [0 for _ in range(MAX)]
dpx[num] = 1
dpy = [0 for _ in range(MAX)]
dpy[num] = 1
for i in range(len(X)):
  px = [0 for _ in range(MAX)]
  px,dpx = dpx,px
  step = X[i]
  for j in range(MAX):
    if j -step >= 0:
      dpx[j] = max(dpx[j],px[j-step])
    if j + step < MAX and i != 0: #一番最初は左に戻れない
      dpx[j] = max(dpx[j],px[j+step])
for i in range(len(Y)):
  py = [0 for _ in range(MAX)]
  py,dpy = dpy,py
  step = Y[i]
  for j in range(MAX):
    if j -step >= 0:
      dpy[j] = max(dpy[j],py[j-step])
    if j + step < MAX:
      dpy[j] = max(dpy[j],py[j+step])
x += num;y+= num
#print(dpx)
#print(dpy)
if dpx[x] == 1 and dpy[y] == 1:
  print("Yes")
else:
  print("No")
Buggy python submission (verdict: Runtime Error):
N, M = map(int,input().split())

michi = [[] for i in range(N)]
for i in range(M):
  tempa, tempb = map(int,input().split())
  michi[tempa-1].append(tempb-1)
  michi[tempb-1].append(tempa-1)
#print(michi)
  
colors = [0 for i in range(N)]

def dfs(v,color):
  colors[v] = color
  for to in michi[v]:
    if colors[to] == color:
      return False
    if colors[to] == 0 and not dfs(to,-color):
      return False
  return True

if dfs(0,1):
  a = colors.count(1)
  b = colors.count(-1)
  #print(colors)
  print(a*b-M)
else:
  print(N*(N-1)//2 - M)

Fixed submission:
import sys
sys.setrecursionlimit(10**7)

N, M = map(int,input().split())

michi = [[] for i in range(N)]
for i in range(M):
  tempa, tempb = map(int,input().split())
  michi[tempa-1].append(tempb-1)
  michi[tempb-1].append(tempa-1)
#print(michi)
  
colors = [0 for i in range(N)]

def dfs(v,color):
  colors[v] = color
  for to in michi[v]:
    if colors[to] == color:
      return False
    if colors[to] == 0 and not dfs(to,-color):
      return False
  return True

if dfs(0,1):
  a = colors.count(1)
  b = colors.count(-1)
  #print(colors)
  print(a*b-M)
else:
  print(N*(N-1)//2 - M)

Buggy python submission (verdict: Runtime Error):
N, M = map(int,input().split())

michi = [[] for i in range(N)]
for i in range(M):
  tempa, tempb = map(int,input().split())
  michi[tempa-1].append(tempb-1)
  michi[tempb-1].append(tempa-1)
print(michi)
  
colors = [0 for i in range(N)]

def dfs(v,color):
  colors[v] = color
  for to in michi[v]:
    if colors[to] == color:
      return False
    if colors[to] == 0 and not dfs(to,-color):
      return False
  return True

if dfs(0,1):
  a = colors.count(1)
  b = colors.count(-1)
  print(colors)
  print(a*b-M)
else:
  print(N*(N-1)//2 - M)

Fixed submission:
import sys
sys.setrecursionlimit(10**7)

N, M = map(int,input().split())

michi = [[] for i in range(N)]
for i in range(M):
  tempa, tempb = map(int,input().split())
  michi[tempa-1].append(tempb-1)
  michi[tempb-1].append(tempa-1)
#print(michi)
  
colors = [0 for i in range(N)]

def dfs(v,color):
  colors[v] = color
  for to in michi[v]:
    if colors[to] == color:
      return False
    if colors[to] == 0 and not dfs(to,-color):
      return False
  return True

if dfs(0,1):
  a = colors.count(1)
  b = colors.count(-1)
  #print(colors)
  print(a*b-M)
else:
  print(N*(N-1)//2 - M)
Buggy python submission (verdict: Time Limit Exceeded):
from heapq import heapify, heappop, heappush

def dijkstra_heap(s,edge): #edgeが複数パターンある場合には引数に入れることも可能 dijkstra_heap(s,edge)
    #始点sから各頂点への最短距離
    d = [float("inf")] * N
    used = [True] * N #True:未確定。始点として探索されたか。というかdが更新されたか。
    d[s] = 0
    used[s] = False
    edgelist = []
    for e in edge[s]:
        heappush(edgelist,e)
    while len(edgelist):
        minedge = heappop(edgelist)
        #まだ使われてない頂点の中からスタートから最小の距離のものを探す
        if not used[minedge[1]]: #すでに探索済みの場合にはスキップして次のプライオリティーキューへ。
            continue
        v = minedge[1]
        d[v] = minedge[0]
        used[v] = False #ここで始点として探索済みにする。
        for e in edge[v]:
            if used[e[1]]: #行き先がすでに始点として探索済みでない場合には値を更新。
                heappush(edgelist,(e[0]+d[v],e[1])) #重みをスタートからの最短重みにするため+d[v]
    return d ##始点sから各頂点への最短距離がアウトプットとなる。

N = int(input())
HQ = [];A = []
for i in range(N):
  temp = list(map(int,input().split()))
  A.append(temp)
  for j in range(i+1,N):
    heappush(HQ,(temp[j],i,j))
#print(HQ)
G = [[] for _ in range(N)]
ans = 0
while HQ:
  dis, start, goal = heappop(HQ)
  d = dijkstra_heap(start,G)
  if d[goal] < dis: #既に近い距離で到達できるなら矛盾
    print(-1); exit()
  elif d[goal] == dis:
    continue
  else: #d[goal] > dis:
    ans += dis
    G[start].append((dis,goal))
    G[goal].append((dis,start))
print(ans)
      



Fixed submission:
import heapq
import sys
N = int(input())

r = [[1]*N for _ in range(N)]
g = [[]*N for _ in range(N)]
all = 0
for i in range(N):
  temp = list(map(int,(input().split())))
  g[i] = temp
  all += sum(temp)
#print(g,all)

for k in range(N):
  for i in range(N):
    for j in range(N):
      if g[i][j] > g[i][k] + g[k][j]:
        print("-1")
        sys.exit()
      elif g[i][j] == g[i][k] + g[k][j] and i != j and j != k and k != i:
        r[i][j] = 0
ans = 0
for i in range(N):
  for j in range(N):
    ans += g[i][j]*r[i][j]

ans = ans//2
print(ans)

Buggy python submission (verdict: Time Limit Exceeded):
import heapq
import sys
N = int(input())

HQ = []
g = [[]*N for _ in range(N)]
all = 0
for i in range(N):
  temp = list(map(int,(input().split())))
  g[i] = temp
  all += sum(temp)
#print(g,all)

for k in range(N):
  for i in range(N):
    for j in range(N):
      if g[i][j] > g[i][k] + g[k][j]:
        print("-1")
        sys.exit()
      elif g[i][j] == g[i][k] + g[k][j] and i != j and j != k and k != i:
        #print(i,j,g[i][j])
        all -= g[i][j]
print(all//2)

Fixed submission:
import heapq
import sys
N = int(input())

r = [[1]*N for _ in range(N)]
g = [[]*N for _ in range(N)]
all = 0
for i in range(N):
  temp = list(map(int,(input().split())))
  g[i] = temp
  all += sum(temp)
#print(g,all)

for k in range(N):
  for i in range(N):
    for j in range(N):
      if g[i][j] > g[i][k] + g[k][j]:
        print("-1")
        sys.exit()
      elif g[i][j] == g[i][k] + g[k][j] and i != j and j != k and k != i:
        r[i][j] = 0
ans = 0
for i in range(N):
  for j in range(N):
    ans += g[i][j]*r[i][j]

ans = ans//2
print(ans)
Buggy python submission (verdict: Runtime Error):
N = int(input())
A = list(map(int,input().split()))
MAX = max(A)
dic = {}
for i in range(N):
  if A[i] not in dic:
    dic[A[i]] = 1
  else:
    dic[A[i]] += 1

ans = []
for i in range(1,MAX+1):
  mae = 0;ima=0;tsugi = 0
  if i in dic:
    ima = dic[i]
  if i != 1:
    if i-1 in dic:
      mae = dic[i-1]
  if i+1 <= MAX:
    if i+1 in dic:
      tsugi = dic[i+1]
  temp = mae + ima + tsugi
  ans.append(temp)
print(max(ans))  
    

Fixed submission:
N = int(input())
A = list(map(int,input().split()))
MAX = max(A)
dic = {}
for i in range(N):
  if A[i] not in dic:
    dic[A[i]] = 1
  else:
    dic[A[i]] += 1

ans = []
for i in range(MAX+1):
  mae = 0;ima=0;tsugi = 0
  if i in dic:
    ima = dic[i]
  if i-1 in dic:
    mae = dic[i-1]
  if i+1 in dic:
    tsugi = dic[i+1]
  temp = mae + ima + tsugi
  ans.append(temp)
print(max(ans))
Buggy python submission (verdict: Time Limit Exceeded):
class UnionFind(object):
  def __init__(self, n=1):
    self.par = [i for i in range(n)]
    self.rank = [0 for _ in range(n)]
    self.size = [1 for _ in range(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 union(self, x, y):
    x = self.find(x)
    y = self.find(y)
    if x != y:
      if self.rank[x] < self.rank[y]:
        x, y = y, x
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      self.par[y] = x
      self.size[x] += self.size[y]
  def is_same(self, x, y):
    return self.find(x) == self.find(y)
  def get_size(self, x):
    x = self.find(x)
    return self.size[x]


from heapq import heapify, heappop, heappush

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()
dx = [];dy =[]
for i in range(N-1):
  tx = X[i+1][0]-X[i][0]
  dx.append((tx,(X[i+1][1],X[i][1])))
  ty = Y[i+1][0]-Y[i][0]
  dy.append((ty,(Y[i+1][1],Y[i][1])))
heapify(dx);heapify(dy)
#print(dx,dy)
visited = set([])
ans = 0
uf = UnionFind(N)
while uf.get_size(0) < N:
  if not dy or dx[0] <= dy[0]:
    cost, loc = heappop(dx)
  else:
    cost, loc = heappop(dy)
  if uf.is_same(loc[0],loc[1]): #すでに接続済みのところはスキップ
    continue
  ans += cost
  #print(cost)
  uf.union(loc[0],loc[1])
print(ans)

Fixed submission:
class UnionFind(object):
  def __init__(self, n=1):
    self.par = [i for i in range(n)]
    self.rank = [0 for _ in range(n)]
    self.size = [1 for _ in range(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 union(self, x, y):
    x = self.find(x)
    y = self.find(y)
    if x != y:
      if self.rank[x] < self.rank[y]:
        x, y = y, x
      if self.rank[x] == self.rank[y]:
        self.rank[x] += 1
      self.par[y] = x
      self.size[x] += self.size[y]
  def is_same(self, x, y):
    return self.find(x) == self.find(y)
  def get_size(self, x):
    x = self.find(x)
    return self.size[x]

import sys
input = sys.stdin.readline

from heapq import heapify, heappop, heappush

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()
dx = [];dy =[]
for i in range(N-1):
  tx = X[i+1][0]-X[i][0]
  dx.append((tx,(X[i+1][1],X[i][1])))
  ty = Y[i+1][0]-Y[i][0]
  dy.append((ty,(Y[i+1][1],Y[i][1])))
heapify(dx);heapify(dy)
#print(dx,dy)
visited = set([])
ans = 0
uf = UnionFind(N)
while uf.get_size(0) < N:
  if not dy or dx[0] <= dy[0]:
    cost, loc = heappop(dx)
  else:
    cost, loc = heappop(dy)
  if uf.is_same(loc[0],loc[1]): #すでに接続済みのところはスキップ
    continue
  ans += cost
  #print(cost)
  uf.union(loc[0],loc[1])
print(ans)