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

"""
n = int(sys.stdin.readline())
a, b = map(int, sys.stdin.readline().split())
c = list(map(int, sys.stdin.readline().split()))
s = [list(map(int,list(sys.stdin.readline()))) for i in range(h)]  # 二次元配列入力　二次元マップみたいな入力のとき

a = 100
b = 0.987654321
print('{0:06d}-{1:6f}'.format(a,b))  # 0埋め, 小数点出力桁指定時のときの出力
000100-0.987654

# 文字列をリストに格納
char_list = list("abcd") # ["a","b","c","d"]
"""

import math
import sys
import itertools
import queue
from fractions import gcd

def lcm(a, b):
    return a * b // gcd(a, b)


mod = 1000000007

if __name__ == "__main__":
    N, Q = map(int, sys.stdin.readline().split())
    origin = sys.stdin.readline()
    for _ in range(Q):
        l, r = map(int, sys.stdin.readline().split())
        s = origin[l-1:r]
        a_flag = False
        ac_num = 0
        for w in s:
            if w == "A":
                a_flag = True
            if a_flag and w == "C":
                ac_num += 1
                a_flag = False
        print(ac_num)


### FIXED CODE ###

"""
n = int(sys.stdin.readline())
a, b = map(int, sys.stdin.readline().split())
c = list(map(int, sys.stdin.readline().split()))
s = [list(map(int,list(sys.stdin.readline()))) for i in range(h)]  # 二次元配列入力　二次元マップみたいな入力のとき

a = 100
b = 0.987654321
print('{0:06d}-{1:6f}'.format(a,b))  # 0埋め, 小数点出力桁指定時のときの出力
000100-0.987654

# 文字列をリストに格納
char_list = list("abcd") # ["a","b","c","d"]
"""

import math
import sys
import itertools
import queue
from fractions import gcd

def lcm(a, b):
    return a * b // gcd(a, b)


mod = 1000000007

if __name__ == "__main__":
    N, Q = map(int, sys.stdin.readline().split())
    origin = sys.stdin.readline()
    dp = [0 for _ in range(N + 1)]
    a_flag = False
    for i in range(N):

        if a_flag and origin[i] == "C":
            dp[i + 1] = dp[i] + 1
            a_flag = False
            continue

        if origin[i] == "A":
            a_flag = True
        else:
            a_flag = False

        dp[i + 1] = dp[i]

    for _ in range(Q):
        l, r = map(int, sys.stdin.readline().split())
        print(dp[r] - dp[l])
### BUGGY CODE ###

from itertools import combinations
 
n, k = [int(item) for item in input().split()]
xy = [[int(item) for item in input().split()] for _ in range(n)]
 
xsort = sorted(xy, key=lambda x: x[0])
ysort = sorted(xy, key=lambda x: x[1])
l = [i for i in range(n)]
 
def count_points_in_rec(x0, x1, y0, y1):
    count = 0
    for x, y in xy:
        if x < x0 or x1 < x:
            continue
        elif y < y0 or y1 < y:
            continue
        count += 1
    return count

ans = 5 * 10**18
for a, b in combinations(l, 2):
    if b - a < k-1:
        continue
    x0 = xsort[a][0]
    x1 = xsort[b][0]
    for c, d in combinations(l, 2):
        if d - c < k-1:
            continue
        y0 = ysort[c][1]
        y1 = ysort[d][1]
        if count_points_in_rec(x0, x1, y0, y1) == k:
            ans = min(ans, (x1-x0) * (y1-y0))

print(ans)

### FIXED CODE ###

from itertools import combinations
 
n, k = [int(item) for item in input().split()]
xy = [[int(item) for item in input().split()] for _ in range(n)]
 
xsort = sorted(xy, key=lambda x: x[0])
ysort = sorted(xy, key=lambda x: x[1])
l = [i for i in range(n)]
 
cum = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(n):
    for j in range(n):
        cum[i+1][j+1] = cum[i+1][j] + cum[i][j+1] - cum[i][j] + ([xsort[i][0], ysort[j][1]] in xy)

def count_points_in_rec(x0, x1, y0, y1):
    point = cum[x1+1][y1+1] - cum[x0][y1+1] - cum[x1+1][y0] + cum[x0][y0]
    return point

ans = 5 * 10**18
comb = []
for a, b in combinations(l, 2):
    if b - a >= k-1:
        comb.append([a, b])
for a, b in comb:
    for c, d in comb:
        if count_points_in_rec(a, b, c, d) == k:
            ans = min(ans, (xsort[b][0]-xsort[a][0]) * (ysort[d][1]-ysort[c][1]))
print(ans)
### BUGGY CODE ###

from heapq import heapify, heappop

nm = list(map(int, input().split()))
n, m = nm[0], nm[1]
d = {}
ab_list = list()
for i in range(n):
    ab = list(map(int, input().split()))
    rem_day, reward = ab[0], ab[1]
    if rem_day in d:
        d[rem_day].append(-reward)
    else:
        d[rem_day] = [-reward]


result = 0

candidates = list()

for rem in range(1, m + 1):
    added_candidates = d.get(rem)
    if added_candidates is not None and len(added_candidates) > 0:
        candidates.extend(added_candidates)

    if len(candidates) > 0:
        heapify(candidates)
        top = heappop(candidates)
        result += -top

print(result)


### FIXED CODE ###

from heapq import heapify, heappop, heappush

nm = list(map(int, input().split()))
n, m = nm[0], nm[1]
d = {}
ab_list = list()
for i in range(n):
    ab = list(map(int, input().split()))
    rem_day, reward = ab[0], ab[1]
    if rem_day in d:
        d[rem_day].append(-reward)
    else:
        d[rem_day] = [-reward]


result = 0

candidates = list()

for rem in range(1, m + 1):
    added_candidates = d.get(rem)
    if added_candidates is not None:
        for ac in added_candidates:
            heappush(candidates, ac)

    if len(candidates) > 0:
        top = heappop(candidates)
        result += -top

print(result)
### BUGGY CODE ###

count = int(input())
num = list(map(int, input().split()))
ans = 1
for i in range(len(num)):
  ans = ans*num[i]
  if ans > 1000000000000000000:
    ans = -1
if ans < 0:
  print(-1)
else:
  print(ans)

### FIXED CODE ###

count = int(input())
A = list(map(int, input().split()))
ans = 1
for i in A:
  if i==0:
    print(0)
    exit()
    
for i in range(len(A)):
  ans = ans*A[i]
  if ans > 1000000000000000000:
    print(-1)
    exit()
    
print(ans)
### BUGGY CODE ###

import numpy as np
from collections import deque
from itertools import product

h, w = map(int, input().split())
c = tuple(map(lambda x: int(x)+1, input().split()))
d = tuple(map(lambda x: int(x)+1, input().split()))
s = np.zeros((h+4, w+4), dtype=np.int8)
for i in range(h):
    s[i+2, 2:-2] = [0 if k == '#' else 1 for k in input()]

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [(0, 0)] + move_a_area]

INF = 10 ** 12
cost = np.full_like(s, INF, dtype=np.int64)
cost[c[0], c[1]] = 0
yet = deque([(c[0], c[1], 0)])
done = deque()

while yet:
    y, x, m = yet.popleft()
    done.append((y, x, m))
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if not s[hh, ww] or cost[hh, ww] <= m:
            continue
        cost[hh, ww] = m
        yet.appendleft((hh, ww, m))
    # Move B
    if not yet:
        while done:
            y, x, m = done.popleft()
            for dx, dy in move_b_area:
                hh, ww = y + dy, x + dx
                if not s[hh, ww] or cost[hh, ww] <= m + 1:
                    continue
                cost[hh, ww] = m + 1
                yet.append((hh, ww, m + 1))

print(v if (v := cost[d[0], d[1]]) < INF else -1)


### FIXED CODE ###

from collections import deque
from itertools import product

h, w = map(int, input().split())
c = tuple(map(lambda x: int(x)-1, input().split()))
d = tuple(map(lambda x: int(x)-1, input().split()))
s = list(input() for _ in range(h))

move_a_area = [(0, -1), (-1, 0), (1, 0), (0, 1)]
move_b_area = [(i, j) for i, j in product(range(-2, 3), repeat=2) if (i, j) not in [(0, 0)] + move_a_area]

cost = [[float('inf')] * w for _ in range(h)]
cost[c[0]][c[1]] = 0
que = deque([(c[0], c[1], 0)])

while que:
    y, x, m = que.popleft()
    # Move A
    for dx, dy in move_a_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m:
            continue
        cost[hh][ww] = m
        que.appendleft((hh, ww, m))
    # Move B
    for dx, dy in move_b_area:
        hh, ww = y + dy, x + dx
        if hh < 0 or h <= hh or ww < 0 or w <= ww or s[hh][ww] == '#' or cost[hh][ww] <= m + 1:
            continue
        cost[hh][ww] = m + 1
        que.append((hh, ww, m + 1))

print(cost[d[0]][d[1]] if cost[d[0]][d[1]] < float('inf') else -1)
### BUGGY CODE ###

n = int(input())
numbers = input()

lst = []
for i in range(n):
  for j in range(i+1,n):
    for k in range(j+1,n):
      pin = ''
      pin = numbers[i] + numbers[j] + numbers[k]
      if pin not in lst:
        lst.append(pin)
print(len(lst))

### FIXED CODE ###

n = int(input())
numbers = input()

lst = []
ans = []
for i in range(n):
  pin = ''
  if numbers[i] not in lst:
    pin += numbers[i]
    lst.append(pin)
    lst2 = []
    for j in range(i+1, n):
      pin += numbers[j]
      if pin[1] not in lst2:
        lst2.append(pin[1])
        lst3 = []
        for k in range(j+1, n):
          pin += numbers[k]
          if pin[2] not in lst3:
            lst3.append(pin[2])
            ans.append(pin)
          if ('0' in lst3) and ('1' in lst3) and ('2' in lst3) and ('3' in lst3) and ('4' in lst3) and ('5' in lst3) and ('6' in lst3) and ('7' in lst3) and ('8' in lst3) and ('9' in lst3):
            break
          pin = pin[0] + pin[1]
      if ('0' in lst2) and ('1' in lst2) and ('2' in lst2) and ('3' in lst2) and ('4' in lst2) and ('5' in lst2) and ('6' in lst2) and ('7' in lst2) and ('8' in lst2) and ('9' in lst2):
        break
      pin = pin[0]
    if ('0' in lst) and ('1' in lst) and ('2' in lst) and ('3' in lst) and ('4' in lst) and ('5' in lst) and ('6' in lst) and ('7' in lst) and ('8' in lst) and ('9' in lst):
      break
print(len(ans))
### BUGGY CODE ###

def solve(n, ax):
    ans = float('inf')
    substract_ax_from_i = []

    for i in range(n):
        substract_ax_from_i.append(ax[i]-i-1)
    #    print('ax: ', ax[i], 'ax-i: ', ax[i]-i-1)
    substract_ax_from_i.sort()
    #print(substract_ax_from_i)

    for i in substract_ax_from_i:
        list_when_choose_i = list(map(lambda x: abs(x-i), substract_ax_from_i))
        sum_of_list_when_choose_i = sum(list_when_choose_i)
        ans = min(ans, sum_of_list_when_choose_i)
        #print(i, list_when_choose_i, ans)

    return ans


if __name__ == '__main__':
    n = int(input())
    ax = list(map(int, input().split()))
    print(solve(n, ax))


### FIXED CODE ###

import numpy as np


#@profile
def solve(n, ax):
    substract_ax_from_i = []

    for i in range(n):
        substract_ax_from_i.append(ax[i]-i-1)
    substract_ax_from_i.sort()
    med = int(np.median(substract_ax_from_i))
    ans = sum(list(map(lambda x: abs(x-med), substract_ax_from_i)))

    return ans


if __name__ == '__main__':
    n = int(input())
    ax = list(map(int, input().split()))
    print(solve(n, ax))
### BUGGY CODE ###

n, k = map(int, input().split())
h = list(map(int, input().split()))

dp = [0] * n
for i in range(1, n):
    tmp = []
    for j in range(1, k + 1):
        if j > i:
            break
        tmp.append(dp[i-j] + abs(h[i]-h[i-j]))
    dp[i] = min(tmp)
print(dp[-1])

### FIXED CODE ###

n, k = map(int, input().split())
h = list(map(int, input().split()))

dp = [0] * n
for i in range(1, n):
    min_tmp = float('inf')
    for j in range(1, k+1):
        if j > i:
            break
        min_tmp = min(min_tmp, dp[i-j] + abs(h[i]-h[i-j]))
    dp[i] = min_tmp
print(dp[-1])
### BUGGY CODE ###

# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
    # combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

def readInt():
    return list(map(int,input().split()))

def main():
    n = int(input())
    for i in range(1,n+1):
        ans = 0
        for j in range(1,int(i**0.5+1)):
            for k in range(1,int(i**0.5+1)):
                for l in range(1,int(i**0.5+1)):
                    if j**2+k**2+l**2+j*k+k*l+j*l==i:
                        ans += 1
        print(ans)
    return

if __name__=='__main__':
    main()


### FIXED CODE ###

# import sys
import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
    # combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
# mod = 998244353
INF = 1<<50

def readInt():
    return list(map(int,input().split()))

def main():
    n = int(input())
    ans = [0 for i in range(n+1)]
    for i in range(1,int(n**0.5)+1):
        for j in range(1,int(n**0.5)+1):
            for k in range(1,int(n**0.5)+1):
                a = i**2+j**2+k**2+i*j+j*k+i*k
                if a<=n:
                    ans[a] += 1
    for i in range(1,n+1):
        print(ans[i])
    return

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

#Python遅すぎて話になんねえ
mod=10**9+7
n,m=map(int,input().split())
s=list(map(int,input().split()))
t=list(map(int,input().split()))
dp=[[0]*(m+1) for i in range(n+1)]
for i in range(n+1):
    dp[i][0]=1
for i in range(m+1):
    dp[0][i]=1
for i in range(n):
    for j in range(m):
        #答え見たらここの添字間違えてただけ…
        #だけど、適当にダブりを引きたくなっただけなので全然方針としてだめ、要復習
        if s[i]==t[j]:
            dp[i+1][j+1]=(dp[i+1][j]+dp[i][j+1])%mod
        else:
            dp[i+1][j+1]=(dp[i+1][j]+dp[i][j+1]-dp[i][j])%mod
print(dp[n][m])

### FIXED CODE ###

mod=10**9+7
n,m=map(int,input().split())
s=list(map(int,input().split()))
t=list(map(int,input().split()))
dp=[[0]*(m+1) for i in range(n+1)]
for i in range(n+1):
    dp[i][0]=1
for i in range(m+1):
    dp[0][i]=1
for i in range(n):
    for j in range(m):
        #答え見たらここの添字間違えてただけ…
        #だけど、適当にダブりを引きたくなっただけなので全然方針としてだめ、要復習
        if s[i]==t[j]:
            dp[i+1][j+1]=(dp[i+1][j]+dp[i][j+1])%mod
        else:
            dp[i+1][j+1]=(dp[i+1][j]+dp[i][j+1]-dp[i][j])%mod
print(dp[n][m])
### BUGGY CODE ###

N = int(input())
S = input()
count = 0

RGBlist = [[S.count('R')],[S.count('G')],[S.count('B')]]


for i in range(1,N):
    RGBlist[0].append(RGBlist[0][-1] - (S[i-1] == 'R'))
    RGBlist[1].append(RGBlist[1][-1] - (S[i-1] == 'G'))
    RGBlist[2].append(RGBlist[2][-1] - (S[i-1] == 'B'))

for i in range(N-2):
    si = S[i]
    
    for j in range(i+1,N-1):
        sj = S[j]
        if si==sj:
            continue
        else:
            RGB = set(['R','G','B'])
            RGB -= set([si,sj])
            k=j+1
            kji=j-i
            if RGB == {'R'}:
                rgb = 0
            elif RGB =={'G'}:
                rgb = 1
            else:
                rgb = 2
            if k+kji-1 < len(S):
                count += RGBlist[rgb][k] - ({S[k+kji-1]} == RGB)
            else:
                count += RGBlist[rgb][k]
            
print(count)


### FIXED CODE ###

N = int(input())
S = input()
count = 0

RGBlist = [[S.count('R')],[S.count('G')],[S.count('B')]]


for i in range(1,N):
    RGBlist[0].append(RGBlist[0][-1] - (S[i-1] == 'R'))
    RGBlist[1].append(RGBlist[1][-1] - (S[i-1] == 'G'))
    RGBlist[2].append(RGBlist[2][-1] - (S[i-1] == 'B'))

for i in range(N-2):
    si = S[i]
    
    for j in range(i+1,N-1):
        sj = S[j]
        if si==sj:
            continue
        else:
            RGB = set(['R','G','B'])
            RGB -= set([si,sj])
            k=j+1
            kji=j-i
            if RGB == {'R'}:
                rgb = 0
            elif RGB =={'G'}:
                rgb = 1
            else:
                rgb = 2
            if k+kji-1 < len(S):
                count += RGBlist[rgb][k] - ({S[k+kji-1]} == RGB)
            else:
                count += RGBlist[rgb][k]
            
print(count)
### BUGGY CODE ###

"""
明らかに無理→最小が2つ無い or 最小同士がペアになってない
(最小から接続する頂点に最小がない)

満たしてる→最小の辺を置いちゃおう
小さい奴からGreedyに置いてく？

自分の周りにendしてるやつ or 大きさが同じやつがあったら繋げちゃう
そのとき白黒はどうでも良さそう？

"""
import sys

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

D = list(map(int,input().split()))

dic2 = [[] for i in range(N)]

for i in range(M):

    U,V = map(int,input().split())
    U -= 1
    V -= 1

    dic2[U].append([D[V],V,i])
    dic2[V].append([D[U],U,i])

for i in range(N):
    dic2[i].sort()
dic = [[] for i in range(N)]
for i in range(N):
    for j in dic2[i]:
        dic[i].append([j[1],j[2]])

#print (dic)

end = [False] * N
color = [0] * N
q = []
ans = [10**9] * M

for i in range(N):
    q.append([D[i],i])
q.sort()
#print (q)

for i in range(N):
    if end[q[i][1]]:
        continue
    flag = False
    for vi in dic[q[i][1]]:
        nexv = vi[0]
        mind = vi[1]
        nowd = q[i][0]
        nowp = q[i][1]
        #print (vi,q[i])

        if end[nexv]:
            flag = True
            color[nowp] = color[nexv] ^ 1
            end[nowp] = True
            ans[mind] = nowd
            break
        elif D[nexv] == nowd:
            
            flag = True
            color[nowp] = color[nexv] ^ 1
            end[nowp] = True
            end[nexv] = True
            ans[mind] = nowd
            break
        break
    #print (ans)

    if not flag:
        print (-1)
        sys.exit()


S = ""
for i in color:
    if i == 0:
        S += "B"
    else:
        S += "W"

print (S)

print (" ".join(map(str,ans)))
        


### FIXED CODE ###

"""
明らかに無理→最小が2つ無い or 最小同士がペアになってない
(最小から接続する頂点に最小がない)

満たしてる→最小の辺を置いちゃおう
小さい奴からGreedyに置いてく？

自分の周りにendしてるやつ or 大きさが同じやつがあったら繋げちゃう
そのとき白黒はどうでも良さそう？

"""
import sys

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

D = list(map(int,input().split()))

dic2 = [[] for i in range(N)]

for i in range(M):

    U,V = map(int,input().split())
    U -= 1
    V -= 1

    if len(dic2[U]) == 0 or dic2[U][0][0] > D[V]:
        dic2[U] = []
        dic2[U].append([D[V],V,i])
    if len(dic2[V]) == 0 or dic2[V][0][0] > D[U]:
        dic2[V] = []
        dic2[V].append([D[U],U,i])


dic = [[] for i in range(N)]
for i in range(N):
    for j in dic2[i]:
        dic[i].append([j[1],j[2]])

#print (dic)

end = [False] * N
color = [0] * N
q = []
ans = [10**9] * M

for i in range(N):
    q.append([D[i],i])
q.sort()
#print (q)

for i in range(N):
    if end[q[i][1]]:
        continue
    flag = False
    for vi in dic[q[i][1]]:
        nexv = vi[0]
        mind = vi[1]
        nowd = q[i][0]
        nowp = q[i][1]
        #print (vi,q[i])

        if end[nexv]:
            flag = True
            color[nowp] = color[nexv] ^ 1
            end[nowp] = True
            ans[mind] = nowd
            break
        elif D[nexv] == nowd:
            
            flag = True
            color[nowp] = color[nexv] ^ 1
            end[nowp] = True
            end[nexv] = True
            ans[mind] = nowd
            break
        break
    #print (ans)

    if not flag:
        print (-1)
        sys.exit()


S = []
for i in color:
    if i == 0:
        S.append("B")
    else:
        S.append("W")

print ("".join(S))

print (" ".join(map(str,ans)))
### BUGGY CODE ###

N=int(input())
a=[str(input())]
s=1
#sは現時点で何個景品が手に入ったかを示す
for i in range (0,N-1):
    #残りn-1回の当選結果について確認
    temp=str(input())#tempはとりあえず入力を受け取る
    t=0
    for j in range(0,s):
      #今までのものに重複がないかチェック
      if temp == a[j]:
        t=t+1
    if t == 0:
        a.append(temp)
        s=s+1
print(s)

### FIXED CODE ###

N=int(input())
a= [input() for i in range(N)]
b=set(a)
print(len(b))
### BUGGY CODE ###

n,q=map(int,input().split())
s=list(map(int,input().replace("AC","1 0 ").replace("A","0 ").replace("T","0 ").replace("C","0 ").replace("G","0 ").split()))
for i in range(q):
  l,r=map(int,input().split())
  print(sum(s[l-1:r-1]))

### FIXED CODE ###

n,q=map(int,input().split())
l=[0 for i in range(n)]
for i,v in enumerate(list(input().replace("AC","X!"))):
    l[i]=l[i-1]+(v=="!")
for c in range(q):
    h,m=map(int,input().split())
    print(l[m-1]-l[h-1])
### BUGGY CODE ###

from fractions import gcd
K = int(input())


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


ans = 0
for a in range(1, K + 1):
    for b in range(1, K + 1):
        for c in range(1, K + 1):
            ans += gcd(gcd(a, b), c)

print(ans)


### FIXED CODE ###

from fractions import gcd
K = int(input())


def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


ans = 0
for a in range(1, K + 1):
    for b in range(1, K + 1):
        for c in range(1, K + 1):
            ans += gcd(gcd(a, b), c)

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

import numpy as np
from queue import Queue

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1

maze = []
for i in range(H):
    maze.append(input())

INF = 10 ** 12

score = np.zeros((H, W), dtype=int)
score[:, :] = INF

score[Ch, Cw] = 0

#visited = np.zeros((H, W), dtype=bool)

candidates = Queue()
candidates.put((Ch, Cw))

walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

while not candidates.empty():
    h, w = candidates.get()
    # move
    for dh, dw in walk:
        y = h + dh
        x = w + dw
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue        
        if maze[y][x] == '.' and score[y, x] > score[h, w]:
            score[y, x] = score[h, w]
            candidates.put((y, x))
    # warp
    #if not moved: 
    for dh, dw in warp:
        y = h + dh
        x = w + dw
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue
        if maze[y][x] == '.' and score[y, x] > score[h, w] + 1:
            score[y, x] = score[h, w] + 1
            candidates.put((y, x))

if score[Dh, Dw] == INF:
    print(-1)
else:
    print (score[Dh, Dw])

### FIXED CODE ###

#import numpy as np
from collections import deque

H, W = map(int, input().split())
Ch, Cw = map(int, input().split())
Dh, Dw = map(int, input().split())

Ch -= 1
Cw -= 1
Dh -= 1
Dw -= 1

maze = [input() for _ in range(H)]

INF = 10 ** 12

score = [[INF] * W for _ in range(H)]

score[Ch][Cw] = 0

candidates = deque()
candidates.append((Ch, Cw))

walk = [(0, 1), (0, -1), (-1, 0), (1, 0)]
warp = [(i, j) for i in range(-2, 3) for j in range(-2, 3) if (i, j) not in [(0, 0)] + walk]

while candidates:
    h, w = candidates.popleft()
    # move
    for dh, dw in walk:
        y = h + dh
        x = w + dw
        s = score[h][w]
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue        
        if maze[y][x] == '.' and score[y][x] > s:
            score[y][x] = s
            candidates.appendleft((y, x))
    # warp
    for dh, dw in warp:
        y = h + dh
        x = w + dw
        s = score[h][w]
        if y < 0 or H <= y:
            continue
        if x < 0 or W <= x:
            continue
        if maze[y][x] == '.' and score[y][x] > s + 1:
            score[y][x] = s + 1
            candidates.append((y, x))

if score[Dh][Dw] == INF:
    print(-1)
else:
    print (score[Dh][Dw])
### BUGGY CODE ###

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

dp = [[0]*(n+1) for i in range(n+1)]

ans = 0
for i in range(n-1, -1, -1):
    for j in range(n-1, i, -1):
        if s[i] == s[j]:
            dp[i][j] = dp[i+1][j+1] + 1
        else:
            dp[i][j] = 0
        ans = max(ans, min(dp[i][j], j-i))

print(ans)

### FIXED CODE ###

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

A = 1234567
MOD = 10000000000000007

def ok(length):
    rolling_hash = 0
    head = pow(A, length, MOD)
    occurence = {}
    for i in range(n):
        rolling_hash = (rolling_hash * A + ord(s[i])) % MOD
        if i - length >= 0:
            rolling_hash = (rolling_hash - head * ord(s[i-length])) % MOD
        if rolling_hash not in occurence:
            occurence[rolling_hash] = []
        occurence[rolling_hash].append(i)

    for key in occurence:
        if occurence[key][-1] - occurence[key][0] >= length:
            return True
    return False

bottom, top = 0, n

while top - bottom > 1:
    mid = (top + bottom) // 2
    if ok(mid):bottom = mid
    else: top = mid

print(bottom)