Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

def main():
  s = ''.join(reversed(input()))
  multiplier = 1
  divisor = 10 ** 9 + 7
  list10 = list(range(10))
  list13 = list(range(13))
  p = [0 for i in list13]
  np = [0 for i in list13]
  if s[0] != '?':
    p[int(s[0])] = 1
  else:
    for j in list10:
      p[j] = 1
  for i in range(1, len(s)):
    multiplier = (10 * multiplier) % 13
    if s[i] != '?':
      r = int(s[i]) * multiplier
      for j in list13:
        np[(j + r) % 13] = p[j]
    else:
      for j in list10:
        r = multiplier * j
        for k in list13:
          np[(k + r) % 13] += p[k]
    for j in list13:
      p[j] = np[j] % divisor
      np[j] = 0
  print(p[5] % divisor)
main()

### FIXED CODE ###

s = ''.join(reversed(input()))
multiplier = 1
divisor = 10 ** 9 + 7
p = [0 for i in range(13)]
if s[0] != '?':
  p[int(s[0])] = 1
else:
  for j in range(10):
    p[j] = 1
for i in range(1, len(s)):
  multiplier = (10 * multiplier) % 13
  np = [0 for j in range(13)]
  if s[i] != '?':
    r = int(s[i]) * multiplier
    for j in range(13):
      np[(j + r) % 13] = p[j]
  else:
    for j in range(10):
      r = j * multiplier
      for k in range(13):
        np[(k + r) % 13] += p[k]
  for j in range(13):
    p[j] = np[j] % divisor
print(p[5] % divisor)
### BUGGY CODE ###

from collections import deque
def main():
    n, m, k  = [int(x) for x in input().split()]
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    aa = 0
    bs = 0
    cc = 0
    for i in range(n + 1):
        c = 0
        if sum(a[:i]) > k:
            break
        else:
            aa = sum(a[:i])
            c = i
            for j in range(bs, m + 1):
                if sum(b[:-j if j != 0 else m]) + aa <= k:
                    c += len(b) - j
                    bs = j
                    break
                else:
                    continue
            if c > cc:
                cc = c
    print(cc)

if __name__ == "__main__":
    main()

### FIXED CODE ###

def main():
    N, M, K  = map(int, input().split())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))
    a, b = [0], [0]
    for i in range(N):
        a.append(a[i] + A[i])
    for i in range(M):
        b.append(b[i] + B[i])
    bs = M
    ans = 0
    for i in range(N + 1):
        if a[i] > K:
            break
        for j in range(bs, -1, -1):
            if b[j] + a[i] <= K:
                bs = j
                break
        ans = max(ans, i + bs)
    print(ans)

if __name__ == "__main__":
    main()
### BUGGY CODE ###

N = int(input())
X = list(map(int, input().split()))
mid = N // 2 - 1
for i in range(N):
    tmp = X[:i]
    tmp.extend(X[i+1:])
    tmp.sort()
    print(tmp[mid])

### FIXED CODE ###

N = int(input())
X = list(map(int, input().split()))
tmp = X[:]
tmp.sort()
mid = N // 2 - 1
low = tmp[mid]
high = tmp[mid + 1]
all = sum(tmp)
for a in X:
    if a <= low:
        print(high)
    else:
        print(low)
### BUGGY CODE ###

import sys
input = lambda: sys.stdin.readline().rstrip()

#https://www.slideshare.net/chokudai/union-find-49066733
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * self.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 False
    if self.parents[x] > self.parents[y]:
      x, y = y, x
    self.parents[x] += self.parents[y]
    self.parents[y] = x
        
  def issame(self, x, y):
    return self.find(x) == self.find(y)
  
  def get_node_members(self):
    return [[j for j in range(self.n) if self.issame(i, j)] for i in range(self.n)]
  
  def size(self, x):
    return -self.parents[self.find(x)]
  
N = list(map(int, input().split()))
uf = UnionFind(N[0])
results = [0 for i in range(N[0])]
for i in range(N[1]):
  x, y = list(map(int, input().split()))
  x, y = x - 1, y - 1
  results[x] += 1
  results[y] += 1
  uf.union(x, y)
#print(uf.parents)

for i in range(N[2]):
  x, y = list(map(int, input().split()))
  x, y = x - 1, y - 1
  if uf.issame(x, y):
  	results[x] += 1
  	results[y] += 1
  
node_members = uf.get_node_members()
#print(node_members, results)

print(" ".join([str(uf.size(i) - results[i] - 1) for i in range(N[0])]))

### FIXED CODE ###

import sys
input = lambda: sys.stdin.readline().rstrip()

#https://www.slideshare.net/chokudai/union-find-49066733
class UnionFind():
  def __init__(self, n):
    self.n = n
    self.parents = [-1] * self.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 False
    if self.parents[x] > self.parents[y]:
      x, y = y, x
    self.parents[x] += self.parents[y]
    self.parents[y] = x
        
  def issame(self, x, y):
    return self.find(x) == self.find(y)
  
  def get_node_members(self):
    return [[j for j in range(self.n) if self.issame(i, j)] for i in range(self.n)]
  
  def size(self, x):
    return -self.parents[self.find(x)]

N = list(map(int, input().split()))
parents = [-1] * N[0]
def find(x):
  if parents[x] < 0:
    return x
  else:
    parents[x] = find(parents[x])
    return parents[x]

def union(x, y):
  x = find(x)
  y = find(y)

  if x == y: return False
  if parents[x] > parents[y]:
    x, y = y, x
  parents[x] += parents[y]
  parents[y] = x
        
def issame(x, y):
  return find(x) == find(y)
  
def size(x):
  return -parents[find(x)]
  

results = [0 for i in range(N[0])]
for i in range(N[1]):
  x, y = list(map(int, input().split()))
  x, y = x - 1, y - 1
  results[x] += 1
  results[y] += 1
  union(x, y)
#print(uf.parents)

for i in range(N[2]):
  x, y = list(map(int, input().split()))
  x, y = x - 1, y - 1
  if issame(x, y):
  	results[x] += 1
  	results[y] += 1
  
#print(node_members, results)

print(" ".join([str(size(i) - results[i] - 1) for i in range(N[0])]))
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
base = []

seen = [0]*n

for i in range(n):
  seen[a[i]-1] =  seen[a[i]-1] + 1

for i in range(n):
   if (seen[i] == 0) or (seen[i] == 1):
      continue
   
   base.append((i+1)+seen[i]*n)

for i in range(n):
  count = 0
  for temp in base:
    now = temp//n
    if temp%n == a[i]:
      now = now - 1
      
    count = count + now*(now-1)//2
    
  print(int(count))


### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))

seen = [0]*n
count = 0
for i in range(n):
  seen[a[i]-1] =  seen[a[i]-1] + 1

for i in range(n):
   if (seen[i] == 0) or (seen[i] == 1):
      continue
   count = count +seen[i]*(seen[i]-1)//2

for i in a:
  ans = count - (seen[i-1]*(seen[i-1]-1))//2 + ((seen[i-1]-2)*(seen[i-1]-1))//2
    
  print(int(ans))
### BUGGY CODE ###

N = int(input())
A = sorted(map(int,input().split()))
B = sorted(map(int,input().split()))
C = sorted(map(int,input().split()))

def f(X,Y,S):
	i,ret = 0, [0 for _ in range(N)]
	for k,x in enumerate(X):
		while x>=Y[i]:
			i += 1
			if i==N: return ret
		if S is None:	ret[k] = N-i
		else:			ret[k] = sum(S[i:])
	return ret

K = f(B,C,None)
K = f(A,B,K)
print(sum(K))


### FIXED CODE ###

import bisect
N = int(input())
A = sorted(map(int,input().split()))
B = sorted(map(int,input().split()))
C = sorted(map(int,input().split()))
print(sum(bisect.bisect_left(A,b)*(N-bisect.bisect_right(C,b)) for b in B))
### BUGGY CODE ###

import sys

N, M = map( int, input().split() )
X_list = sorted( list( map( int, input().split() ) ) )

Dict={}

if N>=M:
	print(0)
	sys.exit()

for i in range(len(X_list)):
	if i==len(X_list)-1:
		break
	Dict[i]=abs(X_list[i]-X_list[i+1])

for n in range(N-1):
	tmp_max=max(Dict, key=Dict.get)
	del Dict[tmp_max]

cnt=0
for v in Dict.values():
	cnt+=v

print(cnt)

### FIXED CODE ###

import sys
import numpy as np

N, M = map( int, input().split() )
X_list = np.array( sorted( list( map( int, input().split() ) ) ) )

diff=np.diff(X_list, n=1)

if N>=M:
	print(0)
	sys.exit()

sorted_diff=np.sort(diff)

cnt=np.sum(sorted_diff[:M-N])

print(cnt)
### BUGGY CODE ###

n = int(input())
A = list(map(int, input().split()))
M = 1000
for i in range(n-1):
    dp = list(range(M+1))
    a, b = A[i], A[i+1]
    for j in range(M+1):
        if j >= a:
            dp[j] = max(dp[j-a]+b, dp[j])
    M = dp[M]
ans = M
print(ans)

### FIXED CODE ###

n = int(input())
A = list(map(int, input().split()))
x, y, z = 1000, 0, 1000
for a in A:
  s1, t1 = divmod(x, a)
  s2, t2 = divmod(z, a)
  s2 += y
  if s1 > s2:
    y, z = s1, t1
  elif s2 > s1:
    y, z = s2, t2
  else:
    y, z = s1, max(t1, t2)
  x = max(x, y*a+z)
ans = x
print(ans)
### BUGGY CODE ###

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

N, K = MAP()
x = LIST()
ans = INF

for i in range(N-K+1):
	S = x[i:i+K]
	tmp = max(S)-min(S) + min(abs(max(S)), abs(min(S)))
	ans = min(ans, tmp)

print(ans)

### FIXED CODE ###

import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10**9 + 7
#from decimal import *

N, K = MAP()
x = LIST()
ans = INF

for i in range(N-K+1):
	tmp = x[i+K-1] - x[i] + min(abs(x[i+K-1]), abs(x[i]))
	ans = min(ans, tmp)

print(ans)
### BUGGY CODE ###

import numpy as np
import sys
sys.setrecursionlimit(10**5)
max = 10**5+5

def dk(start,node,edge):
  ans = [0] * node
  q = [start]
  
  while(len(q) != 0):
    i = q.pop()
    for j, cost in edge[i]:
      ans[j] = (ans[i] + cost)%2
      q.append(j)
  return ans

#入力
N = int(input())
#エッジ
E = [[] for _ in [0]*(max)]

for i in range(N-1):
  a,b,w = (int(x) for x in input().split())
  E[a-1].append((b-1, w))
  E[b-1].append((a-1, w))


ans = dk(0, N, E)

#出力
print(*ans, sep = "\n")
    

### FIXED CODE ###

import numpy as np
import sys
INF = float('inf')
sys.setrecursionlimit(10**5)
max = 10**5+5

def dk(start,node,edge):
  ans = [INF] * node
  ans[0] = 0
  q = [start]
  
  while(len(q) != 0):
    i = q.pop()
    for j, cost in edge[i]:
      if(ans[j] != INF):
        continue
      ans[j] = (ans[i] + cost)%2
      q.append(j)
  return ans

#入力
N = int(input())
#エッジ
E = [[] for _ in [0]*(max)]

for i in range(N-1):
  a,b,w = (int(x) for x in input().split())
  E[a-1].append((b-1, w))
  E[b-1].append((a-1, w))


ans = dk(0, N, E)

#出力
print(*ans, sep = "\n")
### BUGGY CODE ###

n = int(input())
A = input().split()
b = []
for a in A:
    b.append(a)
    b.reverse()
print(' '.join(b))

### FIXED CODE ###

n = int(input())
A = input().split()
if n%2==0:
    print(' '.join(A[1::2][::-1]),end=' ')
    print(' '.join(A[::2]))
else:
    print(' '.join(A[::2][::-1]),end=' ')
    print(' '.join(A[1::2]))
### BUGGY CODE ###

X, Y, Z, K = map(int, input().split())
A = list(map(int, input().split()))
A.sort(reverse=True)
B = list(map(int, input().split()))
B.sort(reverse=True)
C = list(map(int, input().split()))
C.sort(reverse=True)

AB = []
ABC = []
for b in B:
    for a in A:
        AB.append(a+b)
AB.sort(reverse=True)
# AB = AB[:K]
AB = AB[:min(3001, X*Y*Z+1)]

for ab in AB:
    for c in C:
        ABC.append(ab+c)
ABC.sort(reverse=True)
for i in range(K):
    print(ABC[i])

### FIXED CODE ###

x,y,z,k = map(int,input().split())
lisa = list(map(int,input().split()))
lisb = list(map(int,input().split()))
lisc = list(map(int,input().split()))
lisa.sort(reverse=True)
lisb.sort(reverse=True)
lisc.sort(reverse=True)
an = []
ans = []
for num in lisb:
    for nu in lisa:
        an.append(num+nu)
an.sort(reverse=True)
an = an[:min(3001,x*y*z+1)]
for num in lisc:
    for nu in an:
        ans.append(num+nu)
ans.sort(reverse=True)
for i in range(k):
    print(ans[i])
### BUGGY CODE ###

import math
N, M = [int(i) for i in input().split()]

ans = 1
for i in range(1, math.ceil(M / N) + 1):
    if M % i == 0 and M / i >= N:
        ans = i

print(ans)

### FIXED CODE ###

import math
N, M = [int(i) for i in input().split()]

ans = 1
sosu = True if M % 2 == 1 else False

if M % 2 == 1:
    sqrt = int(math.ceil(math.sqrt(M)))
    for i in range(3, sqrt, 2):
        if M % i == 0:
            sosu = False
            break

if sosu == False:
    for i in range(N, M):
        if M % i == 0:
            ans = M / i
            break


print(int(ans))
### BUGGY CODE ###

import sys

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


def dfs(v, p=-1):
    for u in to[v]:
        if u == p:
            continue
        c[u] += c[v]
        dfs(u, v)


N, Q = map(int, input().split())
to = [[] for i in range(N)]  # 隣接リスト
c = [0] * N

for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)

for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    c[p] += x
dfs(0)
print(*c)



### FIXED CODE ###

import sys

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


def dfs(v, p=-1):
    for u in to[v]:
        if u == p:
            continue
        c[u] += c[v]
        dfs(u, v)


N, Q = map(int, input().split())
to = [[] for i in range(N)]  # 隣接リスト
c = [0] * N

for i in range(N - 1):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    to[a].append(b)
    to[b].append(a)

for i in range(Q):
    p, x = map(int, input().split())
    p -= 1
    c[p] += x
dfs(0)
print(*c)
### BUGGY CODE ###

N,K = map(int ,input().split(" "))
list1 = []

#差分して絶対値を求める関数
def abs_ded(A,B):
    return abs(A-B)

#繰り返して、リストに代入していく関数
def make_list(A,B):
    list1.append(abs_ded(A,B))
    while 1:
        key = abs_ded(list1[-1],B)
        if key >= list1[-1]:
            answer = list1[-1]
            break
        else:
            list1.append(key)
    
    print(answer)

make_list(N,K)


### FIXED CODE ###

N,K = map(int ,input().split(" "))

a = N % K
b = K - a

if(a>b):
    print(b)
else:
    print(a)
### BUGGY CODE ###

s = input()
n = len(s)
mod = 2019

lst = [None for i in range(n+1)]
arr = {0:1}

for i in range(1,n+1):
    num = int(s[n-i:])%mod
    if num in arr:
        arr[num]+=1
    else:
        arr[num]=1

ans = 0
for i in arr.values():
    ans += i*(i-1)//2

print(ans)


### FIXED CODE ###

from collections import defaultdict

s = input()
n = len(s)
mod = 2019
DP = [0 for i in range(n+2)]
DP[n+1] = 0

for i in reversed(range(n)):
    DP[i] = (DP[i+1] + int(s[i])*(pow(10,n-i-1,mod)))%mod
DP.pop(-1)

arr = defaultdict(int)
for dp in DP:
    arr[dp]+=1

ans = 0
for i in arr.values():
    ans += i*(i-1)//2
print(ans)
### BUGGY CODE ###

#Python
import sys

N = input()
a = []
for i in range(N):
	a.append(input())
#print a

if 2 not in a:
	print "-1"
	sys.exit()

i=1
#cnt=0
b=[]

while a[i-1]!=2:
	#cnt+=1
	#print a[i-1]
	if i in b:
		print "-1"
		sys.exit()
	b.append(i)
	i=a[i-1]
	#print i,a[i]

#print b
print len(b)+1
#print cnt+1

### FIXED CODE ###

#python
import sys

N = input()
a = []
for i in range(N):
	a.append(input())
#print a

if 2 not in a:
	print "-1"
	sys.exit()

i=1

while a[i-1]!=2:

	if a[i-1]==0:
		print "-1"
		sys.exit()

	#print i,a[i-1]
	before=i
	i=a[i-1]
	a[before-1]=0
	#print a
	

print a.count(0)+1
### BUGGY CODE ###

def dif(n,ab):
    a=[int(i[0]) for i in ab]
    b=[int(i[1]) for i in ab]
    tp=0
    ap=0
    for i in range(n):
        tm=max(a)
        am=max(b)
        if tm>am:
            

            b[a.index(tm)]=0
            a[a.index(tm)]=0
            tp+=tm
        else:
            tp+=a[b.index(am)]
            a[b.index(am)]=0
            b[b.index(am)]=0
        am=max(b)
        a[b.index(am)]=0
        b[b.index(am)]=0
        ap+=am

    return tp-ap

n=int(input())
print(dif(n,[input().split() for i in range(n)]))

### FIXED CODE ###

def dif(n,ab):
    c=[[sum(i),i] for i in ab]
    c.sort(reverse=True)

    ap=0
    bp=0
    for i in range(n):
        if i%2==0:
            ap+=c[i][1][0]
        else:
            bp+=c[i][1][1]


    return ap-bp

n=int(input())
print(dif(n,[list(map(int,input().split())) for i in range(n)]))
### BUGGY CODE ###

from fractions import gcd
n = int(input())
a = list(map(int, input().split()))
if n == 2:
    print(max(a))
    exit()
x = [a[0], gcd(a[0], a[1])]
for i in range(1, n - 2):
    x.append(gcd(x[i], a[i + 1]))
y = [gcd(a[-2], a[-1]), a[-1]]
for i in range(3, n):
    y.insert(0, gcd(y[0], a[-i]))
x.insert(0, y[0])
y.append(x[-1])
ans = 0
for i in range(n):
    ans = max(ans, gcd(x[i], y[i]))
print(ans)


### FIXED CODE ###

from fractions import gcd
n = int(input())
a = list(map(int, input().split()))
if n == 2:
    print(max(a))
    exit()
x = [a[0], gcd(a[0], a[1])]
for i in range(n - 3):
    x.append(gcd(x[i + 1], a[i + 2]))
ans = x[-1]
y = a[-1]
for i in range(1, n - 1):
    z = gcd(y, a[-i])
    ans = max(ans, gcd(x[-i - 1], z))
    y = z
print(max(ans, gcd(y, a[1])))
### BUGGY CODE ###

s = input()
s = [c for c in s]
s.reverse()
s = ''.join(s)
multiplier = 1
divisor = 10 ** 9 + 7
p = [0 for i in range(13)]
if s[0] != '?':
  p[int(s[0])] = 1
else:
  for j in range(10):
    p[j] = 1
for i in range(1, len(s)):
  multiplier = (10 * multiplier) % 13
  if s[i] != '?':
    r = (int(s[i]) * multiplier) % 13
    np = [0 for j in range(13)]
    for j in range(len(p)):
      np[(j + r) % 13] = p[j]
    for j in range(13):
      p[j] = np[j]
  else:
    np = [0 for j in range(13)]
    for j in range(10):
      r = (j * multiplier) % 13
      for k in range(len(p)):
        np[(k + r) % 13] += p[k]
    for j in range(13):
      p[j] = np[j]
print(p[5] % divisor)


### FIXED CODE ###

s = ''.join(reversed(input()))
multiplier = 1
divisor = 10 ** 9 + 7
p = [0 for i in range(13)]
if s[0] != '?':
  p[int(s[0])] = 1
else:
  for j in range(10):
    p[j] = 1
for i in range(1, len(s)):
  multiplier = (10 * multiplier) % 13
  np = [0 for j in range(13)]
  if s[i] != '?':
    r = int(s[i]) * multiplier
    for j in range(13):
      np[(j + r) % 13] = p[j]
  else:
    for j in range(10):
      r = j * multiplier
      for k in range(13):
        np[(k + r) % 13] += p[k]
  for j in range(13):
    p[j] = np[j] % divisor
print(p[5] % divisor)
### BUGGY CODE ###

import queue,sys,copy
sys.setrecursionlimit(10**7)
INF = 10**10
N = int(input())
x = [-INF] + [0 for _ in range(N)] + [INF]
y = [-INF] + [0 for _ in range(N)] + [INF]
for i in range(1,N+1):
    x[i], y[i] = map(int,input().split())
ix = [i for i in range(N+2)]
sort_x_ix = sorted(ix, key=lambda i:x[i])
sort_x = [x[i] for i in sort_x_ix]
sort_y_ix = sorted(ix, key=lambda i:y[i])
sort_y = [y[i] for i in sort_y_ix]
sort_x_inv = [0 for _ in range(N+2)]
sort_y_inv = [0 for _ in range(N+2)]
for i in range(N+2):
    sort_x_inv[sort_x_ix[i]] = i
    sort_y_inv[sort_y_ix[i]] = i

g = [i for i in range(N+1)]
def root(x):
    if g[x] == x : return x
    g[x] = root(g[x])
    return g[x]
q = queue.PriorityQueue()

z = N//2
def put_xy(z):
    i_x = sort_x_inv[z]
    i_y = sort_y_inv[z]
    q.put((sort_x[i_x] - sort_x[i_x-1],z,sort_x_ix[i_x-1]))
    q.put((sort_x[i_x+1] - sort_x[i_x],z,sort_x_ix[i_x+1]))
    q.put((sort_y[i_y] - sort_y[i_y-1],z,sort_y_ix[i_y-1]))
    q.put((sort_y[i_y+1] - sort_y[i_y],z,sort_y_ix[i_y+1]))

put_xy(z)
ans = 0
cnt = N

while True:
    if cnt <= 1: break
    d,s,t = q.get()
    if root(s) != root(t):
        ans += d
        cnt -= 1
        g[t] = g[s]
        put_xy(t)
print(ans)

### FIXED CODE ###

import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    xy = [LI() for _ in range(N)]

    x = [(xy[i][0],i) for i in range(N)]
    y = [(xy[i][1],i) for i in range(N)]

    x.sort()
    y.sort()

    edge = []
    p,i = x[0]
    for q,j in x[1:]:
        edge.append((q-p,i,j))
        p,i = q,j

    p,i = y[0]
    for q,j in y[1:]:
        edge.append((q-p,i,j))
        p,i = q,j

    edge.sort()

    g = [i for i in range(N + 1)]
    g_num = [1 for i in range(N + 1)]

    def find(x):
        if g[x] == x: return x
        g[x] = find(g[x])
        return g[x]

    def union(x, y):
        if find(x) == find(y): return
        if g_num[g[x]] < g_num[g[y]]: x, y = y, x
        g_num[g[x]] += g_num[g[y]]
        g_num[g[y]] = 0
        g[g[y]] = g[x]

    ans = 0
    for v,i,j in edge:
        if find(i) != find(j):
            ans += v
            union(i,j)

    print(ans)



if __name__ == '__main__':
    main()
### BUGGY CODE ###

MOD = 10**9+7
def resolve():
    H, W = list(map(int, input().split()))
    S = [list(input()) for _ in range(H)]
    import collections
    maxdist = 0
    for startx in range(H):
        for starty in range(W):
            if S[startx][starty] == "#":
                continue
            visited = [[False for _ in range(W)] for __ in range(H)]
            q = collections.deque([(startx, starty, 0)])
            while q:
                x, y, dist = q.pop()
                visited[x][y] = True
                maxdist = max(maxdist, dist)
                for dx, dy in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
                    nx = x + dx
                    ny = y + dy
                    if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and visited[nx][ny] is False:
                        q.appendleft((nx, ny, dist+1))
    print(maxdist)
    

if '__main__' == __name__:
    resolve()


### FIXED CODE ###

def resolve():
    H, W = list(map(int, input().split()))
    S = [list(input()) for _ in range(H)]
    import collections
    maxdist = 0

    for startx in range(H):
        for starty in range(W):
            if S[startx][starty] == "#":
                continue
            visited = [[-1 for _ in range(W)] for __ in range(H)]
            visited[startx][starty] = 0
            q = collections.deque([(startx, starty)])
            while q:
                x, y = q.pop()
                for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                    nx = x + dx
                    ny = y + dy
                    if 0 <= nx < H and 0 <= ny < W and S[nx][ny] != "#" and visited[nx][ny] == -1:
                        visited[nx][ny] = visited[x][y] + 1
                        q.appendleft((nx, ny))
            maxdist = max(maxdist,max(sum(visited, [])))
    print(maxdist)
    

if '__main__' == __name__:
    resolve()