Harryxun/stf_run huggingface dataset:
n = int(input())
s = int(input())

flag = False
if s > n:
  print(-1)
  exit()
  
if s == n:
  print(n+1)
  exit()

def chk(b, n):
  if n//b == 0:
    return n
  else:
    return chk(b,n//b) + n%b

for b in range(2, int(n**0.5)+1):
  if chk(b, n) == s:
    print(b)
    flag = True
    exit()

for i in range(int(n**0.5), 0, -1):
  b = (n-s)//i + 1
  if chk(b, n) == s:
    if b > 1:
      print(b)
      flag = True
      exit()

if flag == False:
  print(-1)

### FIXED CODE ###

n = int(input())
s = int(input())

flag = False
if s > n or (n//2)+1<s<n:
  print(-1)
  exit()
  
if s == n:
  print(n+1)
  exit()

def chk(b, n):
  if n//b == 0:
    return n
  else:
    return chk(b,n//b) + n%b

for b in range(2, int(n**0.5)+1):
  if chk(b, n) == s:
    print(b)
    flag = True
    exit()

for i in range(int(n**0.5), 0, -1):
  b = (n-s)//i + 1
  if chk(b, n) == s:
    if b > 1:
      print(b)
      flag = True
      exit()

if flag == False:
  print(-1)
x=input()
c=0
for i in range(len(x)):
  c+=x[i]-'0'
x=int(x)
if x%c==0:
  print("Yes")
else:
  print("No")

### FIXED CODE ###

x=input()
c=0
for i in range(len(x)):
  c+=ord(x[i])-ord('0')
x=int(x)
if x%c==0:
  print("Yes")
else:
  print("No")
from collections import defaultdict
h,w,m = map(int,input().split())
dh = defaultdict(int)
dw = defaultdict(int)
for _ in range(m):
    x,y = map(int,input().split())
    dh[x]+=1
    dw[y]+=1
    l.append((x,y))
m=0
hi=0
for i in dh:
    if dh[i]>m:
        m=dh[i]
        hi=i
c=m
m=0
for i in dw:
    if dw[i]>m:
        m=dw[i]
        if (hi,i) in l:
            m-=1
c+=m
print(c)

### FIXED CODE ###

from collections import defaultdict
h,w,m = map(int,input().split())
dh = defaultdict(int)
dw = defaultdict(int)
l=defaultdict(tuple)
for _ in range(m):
    x,y = map(int,input().split())
    dh[x]+=1
    dw[y]+=1
    l[(x,y)]=1
m = 0
for i in range(1,h+1):
    if dh[i]>m:
        m = dh[i]
        hi=i
c=m
m = 0
for i in range(1,w+1):
    d = dw[i]
    if l[(hi,i)]==1:
        d-=1
    m = max(m,d)
c+=m
m = 0
wi=0
for i in range(1,w+1):
    if dw[i]>m:
        m = dw[i]
        wi=i
c2=m
m = 0
for i in range(1,h+1):
    d = dh[i]
    if l[(i,wi)]==1:
        d-=1
    m = max(m,d)
c2+=m
print(max(c,c2))
x=int(input())
count=0
hugou=1
while True:
  y=(x+count**5)**(1/5)
  if int(y)==y:
    break
  y=(x+((-1)*count)**5)**(1/5)
  if int(y)==y:
    hugou*=(-1)
    break
  count+=1
  
print(int(y),hugou*count)

### FIXED CODE ###

x=int(input())
for i in range(1000):
  for j in range(1000):
    if i**5-j**5==x:
      a,b=i,j
      break
else:
  for k in range(1000):
    for l in range(1000):
      if k**5+l**5==x:
        a,b=k,(-1)*l
        break
        
print(a,b)
import sys
for i in sys.stdin:
    n = int(i)
    num_a = 0
    num_b = 0
    for j in range(n):
        ta, tb = map(int,raw_input().split())
        if ta > tb:
            num_a += (ta+tb)
        elif ta < tb:
            num_b += (ta+tb)
        else:
            num_a += ta
            num_b += tb
    print "%d %d" % (num_a, num_b)

### FIXED CODE ###

while True:
    n = int(raw_input())
    if n == 0:
        break
    num_a = 0
    num_b = 0
    for j in range(n):
        ta, tb = map(int,raw_input().split())
        if ta > tb:
            num_a += (ta+tb)
        elif ta < tb:
            num_b += (ta+tb)
        else:
            num_a += ta
            num_b += tb
    print "%d %d" % (num_a, num_b)
S = list(input())[::-1]
s = len(S)
ans = 0
for i in range(s):
  if S[2*i:(2*i+s)/2+0.5] == S[(2*i+s)/2+0.5:]:
    ans = s-2*i
    break
print(ans)
    


### FIXED CODE ###

S = list(input())[::-1]
s = len(S)
ans = -1
for i in range(1, s):
  if S[2*i:(2*i+s-1)//2+1] == S[(2*i+s-1)//2+1:]:
    ans = s-2*i
    break
print(ans)
4 3 6

### FIXED CODE ###

import sys

read = sys.stdin.read
readline = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7


def main():
    X, A, B = map(int, readline().split())
    if -A+B<=0:
        print('delicious')
    elif 0<-A+B<=X:
        print('safe')
    else:
        print('dangerous')


if __name__ == '__main__':
    main()
# coding: utf-8

# In[ ]:

N = int(input())
V = map(int, input().split())
C = map(int, input().split())


# In[ ]:

import numpy as np


# In[ ]:

bene = V-C
print(np.sum(bene[bene>0]))



### FIXED CODE ###


# coding: utf-8

# In[1]:

N = int(input())
V = list(map(int, input().split()))
C = list(map(int, input().split()))


# In[2]:

import numpy as np


# In[3]:

V = np.array(V)
C = np.array(C)


# In[4]:

bene = V-C
print(np.sum(bene[bene>0]))


# In[ ]:
from itertools import combinations
A,B = map(int,input().split())

divisors = []
n,m = min(A,B), max(A,B)
for i in range(1,int(n**0.5)+1):
  if n%i==0 and m%i==0:
    divisors.append(i)
    p = n//i
    if m%p==0:
      divisors.append(p)

d = max(divisors)
isPrime = [True] * (d+1)
isPrime[0],isPrime[1] = False,False
for i in range(2, int(d ** 0.5) + 1):
  if isPrime[i]:
    for j in range(i * i, d + 1, i):
      isPrime[j] = False

ans = 1
for d in divisors:
  if isPrime[d]:
    ans += 1
print(ans)


### FIXED CODE ###


from collections import Counter
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n //= i
      table.append(i)
    i += 1
  if n > 1:
    table.append(n)
  return table

A,B = map(int,input().split())
p1 = Counter(prime_decomposition(A))
p2 = Counter(prime_decomposition(B))
ans = 1
for p,_ in p1.items():
  if p2[p] > 0:
    ans += 1

print(ans)
def create_edge(fr,to,weight,si):
    edges = []
    if si == '-':
        edges.append((fr,to,weight))
        edges.append((to,fr,0))
    else:
        edges.append((to,fr,-weight))
    return edges

#????????????????????´???-1?????????
def bellmanford(edges, length):
    start_vertex = 0
    
    distance = [float('inf')] * length
    distance[start_vertex] = 0
    
    for i in range(length):
        for fr, to, weight in edges:
            if distance[to] > distance[fr] + weight:
                distance[to] = distance[fr] + weight

    for fr, to, weight in edges:
        if distance[to] > distance[fr] + weight:
           return -1
    return max(distance)

import sys
import re
import math
import itertools

n,c = map(int, f.readline().split())

p = re.compile('(\d+)(\D+)(\d+)(\D+)(\d+)')
constraints = [p.match(line).groups() for line in f]

fixed_edges = []
floating_edges = []
for ai, oi, bi, si, di in constraints:
    fr,to,weight = int(ai) - 1,int(bi) - 1,int(di)

    if oi == '*':
        floating_edges.append((create_edge(fr,to,weight,si),create_edge(to,fr,weight,si)))
    else:
        if oi == '>=':
            fr, to = to, fr
        fixed_edges.extend(create_edge(fr,to,weight,si))

distance = []
for edges in itertools.product(*floating_edges):
    distance.append(bellmanford(fixed_edges + [y for x in edges for y in x], n))

print(max(distance))

### FIXED CODE ###

import sys
import re
import math
import itertools
def create_edge(fr,to,weight,si):
    edges = []
    if si == '-':
        edges.append((fr,to,weight if to else 0))
        edges.append((to,fr,0))
    else:
        edges.append((to,fr,-weight))
    return edges
#????????????????????´???-1?????????
def bellmanford(edges, length):
    start_vertex = 0
    
    distance = [float('inf')] * length
    distance[start_vertex] = 0
    
    for i in range(length):
        for fr, to, weight in edges:
            if distance[to] > distance[fr] + weight:
                distance[to] = distance[fr] + weight

    for fr, to, weight in edges:
        if distance[to] > distance[fr] + weight:
           return -1
    if min(distance[1:]) < 0:
        return -1
    return max(distance)
f = sys.stdin


n,c = map(int, f.readline().split())

p = re.compile('(\d+)(\D+)(\d+)(\D+)(\d+)')
constraints = [p.match(line).groups() for line in f]

fixed_edges = []
floating_edges = []
for ai, oi, bi, si, di in constraints:
    fr,to,weight = int(ai) - 1,int(bi) - 1,int(di)

    if oi == '*':
        if fr and to:
            floating_edges.append((create_edge(fr,to,weight,si),create_edge(to,fr,weight,si)))
            continue
        oi = '<=' if fr < to else '>='

    if oi == '>=':
        fr, to = to, fr
    
    fixed_edges.extend(create_edge(fr,to,weight,si))
distance = []
for edges in itertools.product(*floating_edges):
    distance.append(bellmanford(fixed_edges + [y for x in edges for y in x], n))
print(max(distance))
N = int(input())
say = []
for i in range(N):
    A = int(input())
    t = []
    for j in range(A):
        s = list(map(int,input().split()))
        t.append(s)
    say.append(t)

a = 0
for i in range(2**N):
    judge = 1
    c = 0
    
    for j in range(N):
        if judge = 0:
            break
        if ((i >> j) & 1):
            for k in range(len(say[j])):
                if ((i>>(say[j][k][0]-1))&1) != say[j][k][1]:
                    judge = 0
        else:
            for k in range(len(say[j])):
                if ((i>>(say[j][k][0]-1))&1) == say[j][k][1]:
                    judge = 0
    
    if judge:
        c = bin(i).count("1")
        a = max(a,c)
print(a)

### FIXED CODE ###

N = int(input())
say = []
for i in range(N):
    A = int(input())
    t = []
    for j in range(A):
        s = list(map(int,input().split()))
        t.append(s)
    say.append(t)

a = 0
for i in range(2**N):
    judge = 1 
    
    for j in range(N):
        if judge == 0:
            break
        if ((i >> j) & 1):
            for k in range(len(say[j])):
                if ((i>>(say[j][k][0]-1))&1) != say[j][k][1]:
                    judge = 0
    
    if judge:
        c = bin(i).count("1")
        a = max(a,c)
print(a)
if __name__ == "__main__":
	print (S[:4].upper() + " " + S[4:].upper())

### FIXED CODE ###

s=input()
print(s[:4]+ " "+s[4:])
n=int(input())
for i in range(1,n+1):
  if((i%3==0)and(i%5==0)):
    continue
  elif(i%3==0):
    continue
  elif((i%5==0)):
    continue
  else:
    c+=i
print(c)
  

### FIXED CODE ###

n=int(input())
c=0
for i in range(1,n+1):
  if((i%3==0)and(i%5==0)):
    continue
  elif(i%3==0):
    continue
  elif((i%5==0)):
    continue
  else:
    c+=i
print(c)
N = int(input())

count = 0

for i in range(N+1):
  l, r = map(int, input().split())
  count += r-l+1
  
print(count)
  

### FIXED CODE ###

N = int(input())
a=[list(map(int,input().split())) for i in range(N)]
count = 0

for i in range(N):
  count += a[i][1] - a[i][0] + 1
  
print(count)
N=int(input())
s=set()
for i in range(N):
  a=set(int(input()))
  s^=a
print(len(a))

### FIXED CODE ###

N=int(input())
s=set()
for i in range(N):
  a=int(input())
  if a in s:
    s.remove(a)
  else:
    s.add(a)
print(len(s))
yandy
n, m = map(int, input().split())

student = []

for i in range(n):
    a, b = map(int, input().split())
    student.append((a, b))

point = []

for j in range(m):
    c, d = map(int, input().split())
    point.append((c, d))

for a, b in student:
    length = 10 ** 10
    pn = 0
    for j in range(m):
        c, d = point[j]
        if abs(a-c) + abs(b-d) < length:
            length = abs(a-c) + abs(b-d)
            pn = j + 1
    print(pn)


### FIXED CODE ###

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

for a,b in student:
  length=10**10
  pn=0
  for j in range(m):
    c,d=point[j]
    if abs(a-c)+abs(b-d)<length:
      length=abs(a-c)+abs(b-d)
      pn=1+j
  print(pn)
while True:
    m,f,r=map(raw_int, input().split())
    s=m+f
    if m==-1 and f==-1 and r==-1:
        break
    elif m==-1 or f==-1 or s <30:
        print 'F'
    elif s <50 and r <50:
        print 'D'
    elif s <65:
        print 'C'
    elif s <80:
        print 'B'
    else:
        print 'A'

### FIXED CODE ###

while True:
    m,f,r=map(int, raw_input().split())
    s=m+f
    if m==-1 and f==-1 and r==-1:
        break
    elif m==-1 or f==-1 or s <30:
        print 'F'
    elif s <50 and r <50:
        print 'D'
    elif s <65:
        print 'C'
    elif s <80:
        print 'B'
    else:
        print 'A'
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
k = int(input())
lis = list(a, b, c, d, e)
if max(lis) - min(lis) <= k:
    print('Yay!')
else:
    print(':(')

### FIXED CODE ###

a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
k = int(input())
if e - a <= k:
    print('Yay!')
else:
    print(':(')
n, k = map(int, input().split())
x = list(map(int, input().split()))


def check(now, k, t, logs, ans):
    if now in logs:
        return ans
    logs.append(now)
    if k == 0:
        return min(ans, t)

    if len(x) > now + 1:
        ans = min(ans, check(now + 1, k - 1, t +
                             abs(x[now + 1] - x[now]), logs[::], ans))
    if now - 1 >= 0:
        ans = min(ans, check(now - 1, k - 1, t +
                             abs(x[now - 1] - x[now]), logs[::], ans))
    return ans


def main():
    ans = abs(sum(x))
    for i, v in enumerate(x):
        ans = min(ans, check(i, k - 1, abs(v), [], ans))
    print(ans)


main()


### FIXED CODE ###

def main():
    n, k = map(int, input().split())
    x = list(map(int, input().split()))

    i = 0
    ans = 10 ** 8 * n
    while i < n - k + 1:
        lr = abs(x[i]) + abs(x[i] - x[i + k - 1])
        rl = abs(x[i + k - 1]) + abs(x[i] - x[i + k - 1])
        i += 1
        ans = min(ans, lr, rl)
    print(ans)


main()
import math
n = int(input())
m = 1000000007
l = list(map(int,input().split()))
a,v=1,1
for i in l:
    b = math.gcd(a,i)
    a = ((a*i)%m)*(pow(b,m-2,m))%m

ans=0
for i in range(n):
    ans+=a*pow(l[i],m-2,m)
    ans=ans%m
print(ans)

### FIXED CODE ###

from fractions import gcd

N = int(input())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7
l = 1
res = 0
for x in a:
  l = x * l // gcd(x, l)
l %= mod
for x in a:
  res += l * pow(x, mod - 2, mod)
  res %= mod
print(res)
h, w = map(int, input().split())
  print((h*w+1)//2)

### FIXED CODE ###

h, w = map(int, input().split())
if(h == 1 or w == 1):
  print(1)
else:
  print((h*w+1)//2)
n = input()
taro, hanako = 0, 0
for number in n:
  taro_string, hanako_string = raw_input().split()
  if taro_string > hanako_string:
    taro += 3
  elif hanako_string > taro_string:
    hanako += 3
  else:
    taro += 1
    hanako += 1
print taro, hanako 

### FIXED CODE ###

n = input()
taro, hanako = 0, 0
for number in range(n):
  taro_string, hanako_string = raw_input().split()
  if taro_string > hanako_string:
    taro += 3
  elif hanako_string > taro_string:
    hanako += 3
  else:
    taro += 1
    hanako += 1
print taro, hanako
import decimal
a,b = map(decimal,input().split())
print(int(a*b))


### FIXED CODE ###

a,b = input().split()
na = int(a)
nb100 = (int(b[0])*100+int(b[2:]))
ans = na*nb100
print(ans//100)
def solve(g):
    dp = [-1]*len(g)
    def _solve(f):
        if dp[f] == -1:
            dp[f] = 0
            for c in g[f]:
                dp[f] = max(dp[f], 1 + _solve(c))
        return dp[f]
    for f in range(len(g)):
        _solve(f)
    # print(dp)
    return max(dp)

n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
    f, t = map(int, input().split())
    g[f-1].append(t-1)

print(solve(g))

### FIXED CODE ###

import sys
sys.setrecursionlimit(10000)

def solve(g):
    dp = [-1]*len(g)
    def _solve(f):
        if dp[f] == -1:
            dp[f] = 0
            for c in g[f]:
                dp[f] = max(dp[f], 1 + _solve(c))
        return dp[f]
    for f in range(len(g)):
        _solve(f)
    # print(dp)
    return max(dp)

n, m = map(int, input().split())
g = [[] for _ in range(n)]
for _ in range(m):
    f, t = map(int, input().split())
    g[f-1].append(t-1)

print(solve(g))
class Checker:
    d = {
        1: { 2: (3,4,5,6), 3: (5,2,4,6), 4: (2,5,3,6), 5: (4,3,2,6) },
        2: { 1: (4,3,6,5), 3: (1,6,4,5), 4: (6,1,3,5), 6: (3,4,1,5) },
        3: { 1: (2,5,6,4), 2: (6,1,5,4), 5: (1,6,2,4), 6: (5,2,1,4) },
        4: { 1: (5,2,6,3), 2: (1,6,5,3), 5: (6,1,2,3), 6: (2,5,1,3) },
        5: { 1: (3,4,6,2), 3: (6,1,4,2), 4: (1,6,3,2), 6: (4,3,1,2) },
        6: { 2: (4,3,5,1), 3: (2,5,4,1), 4: (5,2,3,1), 5: (3,4,2,1) }
        }

    def __init__(self, s):
        l = s.split()
        self.tbl = {}
        for c,i in zip(l, range(1,7)):
            if c in self.tbl:
                self.tbl[c].append(i)
            else:
                self.tbl[c] = [i]
        self.pip = dict(zip(range(1,7), l))

    def __call__(self, s):
        l = s.split()
        for i0 in self.tbl[l[0]]:
            for i1 in self.tbl[l[1]]:
                if i1 in self.d[i0]:
                    for i,j in zip(self.d[i0][i1], range(2,6)):
                        if self.pip[i] != l[j]:
                            break
                    else:
                        return True
        return False

def g():
    n = int(input()) - 1
    c = Checker(input())
    for _ in range(n):
        yield c(input())

if any(g()):
    print("No")
else:
    print("Yes")

### FIXED CODE ###

class Checker:
    d = {
        1: { 2: (3,4,5,6), 3: (5,2,4,6), 4: (2,5,3,6), 5: (4,3,2,6) },
        2: { 1: (4,3,6,5), 3: (1,6,4,5), 4: (6,1,3,5), 6: (3,4,1,5) },
        3: { 1: (2,5,6,4), 2: (6,1,5,4), 5: (1,6,2,4), 6: (5,2,1,4) },
        4: { 1: (5,2,6,3), 2: (1,6,5,3), 5: (6,1,2,3), 6: (2,5,1,3) },
        5: { 1: (3,4,6,2), 3: (6,1,4,2), 4: (1,6,3,2), 6: (4,3,1,2) },
        6: { 2: (4,3,5,1), 3: (2,5,4,1), 4: (5,2,3,1), 5: (3,4,2,1) }
        }

    def __init__(self, s):
        l = s.split()
        self.tbl = {}
        for c,i in zip(l, range(1,7)):
            if c in self.tbl:
                self.tbl[c].append(i)
            else:
                self.tbl[c] = [i]
        self.pip = dict(zip(range(1,7), l))

    def __call__(self, s):
        l = s.split()

        if not (l[0] in self.tbl):
            return False
        if not (l[1] in self.tbl):
            return False

        for i0 in self.tbl[l[0]]:
            for i1 in self.tbl[l[1]]:
                if i1 in self.d[i0]:
                    for i,j in zip(self.d[i0][i1], range(2,6)):
                        if self.pip[i] != l[j]:
                            break
                    else:
                        return True
        return False

def g():
    n = int(input()) - 1
    c = Checker(input())
    for _ in range(n):
        yield c(input())

if any(g()):
    print("No")
else:
    print("Yes")
N = int(input())
L = list(map(int, input().split()))
res = 0
def dfs(A):
    global res, L
    ans = [i for i, v in enumerate(A) if v == 1]
    if len(A) == N:
        if len(ans) == 3:
            a, b, c = L[ans[0]], L[ans[1]], L[ans[2]]
            if a < (b + c) and b < (c + a) and c < (a + b):
                res += 1
        return
    elif len(ans) == 3:
        a, b, c = L[ans[0]], L[ans[1]], L[ans[2]]
        if a < (b + c) and b < (c + a) and c < (a + b):
            res += 1
        return
    else:
        for v in range(2):
            A.append(v)
            dfs(A)
            A.pop()
dfs([])
print(res)

### FIXED CODE ###

import bisect
N = int(input())
L = list(map(int, input().split()))
ans = 0
L.sort()
for a_i in range(N-2):
    for b_j in range(a_i+1, N-1):
        c_idx = bisect.bisect_left(L, L[a_i]+L[b_j])
        if c_idx > b_j:
            ans += c_idx - b_j - 1
print(ans)
N = int(input())
S = str(input())

if N%2==0:
    N = int(N)
else:
    print('No')
    sys.exit()
S_1 = S[:N//2]

S_2 = S_1+S_1
if S == S_2:
    print("Yes")
else:
    print("No")

### FIXED CODE ###

import sys
N = int(input())
S = str(input())

if N%2==1:
    print('No')
    sys.exit()

S_1 = S[:N//2]

S_2 = S_1+S_1
if S == S_2:
    print("Yes")
else:
    print("No")
N = int(input())
x, y, h = [[0]*N, [0]*N, [0]*N]
for n in range(N):
  x[n], y[n], h[n] = map(int, input().split())

def f():
  for xx in range(101):
    for yy in range(101):
      height = [-1 for _ in range(N)]
      for n in range(N):
        height[n]= abs(x[n]-xx)+abs(y[n]-yy)+h[n]
        if set(height[:n+1]) == {}:
          break
      if len(set(height)) == 1:
        return [xx, yy, height[0]]
print(*f())

### FIXED CODE ###

N = int(input())
x, y, h = [[0]*N, [0]*N, [0]*N]
for n in range(N):
  x[n], y[n], h[n] = map(int, input().split())
  if h[n] > 0:
    hi = n

def g(xx, yy, height):
  for n in range(N):
    if max(height-abs(xx-x[n])-abs(yy-y[n]), 0) != h[n]:
      return False
  return True

def f():
  for xx in range(101):
    for yy in range(101):
      height = abs(xx-x[hi])+abs(yy-y[hi])+h[hi]
      if g(xx, yy, height) is True:
        return [xx, yy, height]
print(*f())
import sys
from collections import defaultdict
finput=lambda:sys.stdin.readline().strip()
sys.setrecursionlimit(10*9)

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())
    xy=dict((tuple(map(int,finput().split())),i) for i in range(n))
    coor=sorted(list(iter(xy)),key=lambda e:e[0])
    cost = lambda e,f:min(abs(e[0]-f[0]),abs(e[1]-f[1]))
    ew=dict(((xy[coor[i]],xy[coor[i+1]]),cost(coor[i],coor[i+1]))for i in range(n-1))
    coor.sort(key=lambda e:e[1])
    ew.update(dict(((xy[coor[i]],xy[coor[i+1]]),cost(coor[i],coor[i+1]))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()


### FIXED 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()