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

from collections import deque
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())

maze = [list(input()) for i in range(h)]
ans = [[-1]*w for i in range(h)]
ans[ch-1][cw-1]=0
dx=[0,1,0,-1]
dy=[1,0,-1,0]
count=0

def bfs(ans):
  qu = deque([])
  qu.append([cw-1,ch-1])
  while qu:
    zahyou=qu.popleft()
    x=zahyou[0]
    y=zahyou[1]

    for i in range(x-2,x+3):
      for j in range(y-2,y+3):
        if (x==i and y==j):
          continue
        if 0<=i<w and 0<=j<h:
          if maze[j][i]=="." and (ans[j][i]>ans[y][x] or ans[j][i]==-1):
            if (x==i and y==j+1) or (x==i+1 and y==j) or (x==i-1 and y==j) or (x==i and y==j-1):
              qu.append([i,j])
              ans[j][i] = ans[y][x]
            elif ans[j][i]>ans[y][x]+1 or ans[j][i]==-1:
              ans[j][i]=(ans[y][x]+1)
              qu.append([i,j])

bfs(ans)
print(ans[dh-1][dw-1])
#for i in ans:
#  print(*i)
  



### FIXED CODE ###

from collections import deque
h,w=map(int,input().split())
ch,cw=map(int,input().split())
dh,dw=map(int,input().split())

maze = [list(input()) for i in range(h)]
ans = [[-1]*w for i in range(h)]

dx=[0,1,0,-1]
dy=[1,0,-1,0]

ans[ch-1][cw-1]=0
def bfs(ans):
  qu = deque([])
  qu.append([cw-1,ch-1])
  while qu:
    zahyou=qu.popleft()
    x=zahyou[0]
    y=zahyou[1]
    count=0
    for i in range(4):
      if 0 <= x+dx[i] < w and 0 <= y+dy[i] < h:
        if maze[y+dy[i]][x+dx[i]]=="." and (ans[y+dy[i]][x+dx[i]]>ans[y][x] or ans[y+dy[i]][x+dx[i]]==-1):
          qu.appendleft([x+dx[i],y+dy[i]])
          ans[y+dy[i]][x+dx[i]] = ans[y][x]
          count+=1
    if count!=4:
      for i in range(x-2,x+3):
        for j in range(y-2,y+3):
          if 0<=i<w and 0<=j<h:
            if maze[j][i]=="." and (ans[j][i]>ans[y][x]+1 or ans[j][i]==-1):
              ans[j][i]=(ans[y][x]+1)
              qu.append([i,j])

bfs(ans)
print(ans[dh-1][dw-1])
### BUGGY CODE ###

N=int(input())
d=list(map(int,input().split()))
n=0
for k in range(1,10**5+1):
  m=0
  for b in d:
    if b<k:
      m+=1
  if m==N/2:
    n+=1
print(n)

### FIXED CODE ###

N=int(input())
d=sorted(list(map(int,input().split())))
print(d[int(N/2)]-d[int(N/2-1)])
### BUGGY CODE ###

MOD = 10**9 + 7

class Combination:
    def __init__(self, size):
        self.size = size + 2
        self.fact = [1, 1] + [0] * size
        self.factInv = [1, 1] + [0] * size
        self.inv = [0, 1] + [0] * size

        for i in range(2, self.size):
            self.fact[i] = self.fact[i - 1] * i % MOD
            self.inv[i] = -self.inv[MOD % i] * (MOD // i) % MOD
            self.factInv[i] = self.factInv[i - 1] * self.inv[i] % MOD

    def npr(self, n, r):
        if n < r or n < 0 or r < 0:
            return 0
        return self.fact[n] * self.factInv[n - r] % MOD

    def ncr(self, n, r):
        if n < r or n < 0 or r < 0:
            return 0
        return self.fact[n] * (self.factInv[r] * self.factInv[n - r] % MOD) % MOD

    def nhr(self, n, r):  # 重複組合せ: x_1 + ... + x_n = r
        return self.ncr(n + r - 1, n - 1)

K = int(input())
S = input()
N = len(S)

comb = Combination(N + K + 100)

ans = 0
for l in range(K + 1):
    r = K - l
    ans += pow(25, l, MOD) * comb.nhr(N, l) * pow(26, r, MOD)
    ans %= MOD

print(ans)


### FIXED CODE ###

MOD = 10**9 + 7

class Combination:
    def __init__(self, size):
        self.size = size + 2
        self.fact = [1, 1] + [0] * size
        self.factInv = [1, 1] + [0] * size
        self.inv = [0, 1] + [0] * size

        for i in range(2, self.size):
            self.fact[i] = self.fact[i - 1] * i % MOD
            self.inv[i] = -self.inv[MOD % i] * (MOD // i) % MOD
            self.factInv[i] = self.factInv[i - 1] * self.inv[i] % MOD

    def npr(self, n, r):
        if n < r or n < 0 or r < 0:
            return 0
        return self.fact[n] * self.factInv[n - r] % MOD

    def ncr(self, n, r):
        if n < r or n < 0 or r < 0:
            return 0
        return self.fact[n] * (self.factInv[r] * self.factInv[n - r] % MOD) % MOD

    def nhr(self, n, r):  # 重複組合せ: x_1 + ... + x_n = r
        return self.ncr(n + r - 1, n - 1)

K = int(input())
S = input()
N = len(S)

comb = Combination(N + K + 100)

ans = 0
for l in range(K + 1):
    r = K - l
    ans += pow(25, l, MOD) * comb.nhr(N, l) * pow(26, r, MOD)
    ans %= MOD

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

import sys
input = sys.stdin.readline

N,M = map(int,input().split())
S = [[]for i in range(N)]
for i in range(M):
    u,v = map(int,input().split())
    S[v-1].append(u-1)
T,St = map(int,input().split())

D = [[float('inf')]*3 for i in range(N)]
D[St-1][0] = 0
queue = [St-1]
hoge = [0]*N
i = 0
while queue != []:
    i += 1
    l = 0
    for q in queue:
        for s in S[q]:
            if D[s][i%3] > i:
                D[s][i%3] = i
                if not s in hoge[:l]:
                    hoge[l] = s
                    l += 1
    queue = hoge[:l]
    if D[T-1][0] != float('inf'):
        break
if D[T-1][0] == float('inf'):
    print(-1)
else:
    print(D[T-1][0]//3)

### FIXED CODE ###

import sys
input = sys.stdin.readline

N,M = map(int,input().split())
S = [[]for i in range(N)]
for i in range(M):
    u,v = map(int,input().split())
    S[u-1].append(v-1)
St,T = map(int,input().split())

D = [[float('inf')]*3 for i in range(N)]
D[St-1][0] = 0
queue = [St-1]
i = 0
while queue != []:
    i += 1
    hoge = []
    for q in queue:
        for s in S[q]:
            if D[s][i%3] > i:
                D[s][i%3] = i
                if not s in hoge:
                    hoge.append(s)
    queue = hoge[:]
    if D[T-1][0] != float('inf'):
        break
if D[T-1][0] == float('inf'):
    print(-1)
else:
    print(D[T-1][0]//3)
### BUGGY CODE ###

n,k = list(map(int, input().split()))
pl = list(map(int, input().split()))
cl = list(map(int, input().split()))
sc = 0
max = 0

for i in range(0,n):
  pos = i
  sc = 0
  for j in range(0,k):
    pos = pl[pos] - 1
    sc += cl[pos]
    if max < sc or max == 0:
      max = sc

print(max)

### FIXED CODE ###

from itertools import accumulate 
#acumulate [a[0], a[0]+a[1], a[0]+...]
 
n, k = map(int, input().split())
p = [int(x) - 1 for x in input().split()]
c = list(map(int, input().split()))
ans = -(10 ** 18)
 
for i in range(n):
    pos = i
    scores = []
    while True:
        pos = p[pos]
        scores.append(c[pos])
        if pos == i:
            break
    m = len(scores)
    s = list(accumulate(scores))
    for j in range(min(m, k)):
        x = (k - j - 1) // m
        ans = max(ans, s[j], s[j] + s[-1] * x)
 
print(ans)
### BUGGY CODE ###

S = input()
le = len(S)
S = S[::-1]

mod = 10**9 + 7

mo = 1

dp = ([1]*10 if S[0] == "?" else [int(x == int(S[0])) for x in range(10)]) + [0]*3

i = 1
while i != le:
    mo = (mo * 10)%13
    a = [0]*13
    if S[i] == "?":
        j = 0
        while j != 10:
            k = 0
            while k != 13:
                a[(k+mo*j)%13] += dp[k]
                a[(k+mo*j)%13] %= mod
                k += 1
            j += 1
    else:
        j = int(S[i])
        k = 0
        while k != 13:
            a[(k+mo*j)%13] += dp[k]
            a[(k+mo*j)%13] %= mod
            k += 1
    dp = a
    i += 1

print(dp[5])

### FIXED CODE ###

import sys

for S in sys.stdin:
    break
S = S.strip()
le = len(S)

mod = 10**9 + 7

mo = 1

dp = ([1]*10 if S[-1] == "?" else [int(x == int(S[-1])) for x in range(10)]) + [0]*3

i = 1
while i != le:
    mo = (mo * 10)%13
    a = [0]*13
    if S[-i-1] == "?":
        j = 0
        while j != 10:
            k = 0
            while k != 13:
                a[(k+mo*j)%13] += dp[k]
                a[(k+mo*j)%13] %= mod
                k += 1
            j += 1
    else:
        j = int(S[-i-1])
        k = 0
        while k != 13:
            a[(k+mo*j)%13] += dp[k]
            a[(k+mo*j)%13] %= mod
            k += 1
    dp = a
    i += 1

print(dp[5])
### BUGGY CODE ###

N, M = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(M)]
mid = []
AB.sort()
for ab in AB:
    if ab[0] == 1:
        for  cd in AB:
            if ab[1] == cd[0] and cd[1] == N:
                print("POSSIBLE")
                exit()
print("IMPOSSIBLE")

### FIXED CODE ###

N, M = map(int,input().split())
AB = []
for _ in range(M):
    a,b = map(int,input().split())
    if  a == 1 or b== N:
        AB.append((a,b))
set1 = set()
set2 = set()
for ab in AB:
    if ab[0] == 1:
        set1.add(ab[1])
    if ab[1] == N:
        set2.add(ab[0])
if set1 & set2:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")
### BUGGY CODE ###

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

c = collections.Counter(a)

comon = c.most_common()
ans = 0
for i in comon:
  if i[1] != 1:
  	ans += (i[1]*(i[1]-1)//2)
  
for i in a:
    for j in comon:
      if i == j[0]:
        co = j[1]
        break
    print(ans-(co*(co-1)//2)+((co-1)*(co-2)//2))

      

### FIXED CODE ###

import collections
n = int(input())
a = list(map(str,input().split()))
ls = [i for i in range(2*10**5)]
c = collections.Counter(a)
comon = c.most_common()
ans = 0

for i in comon:
    if i != 1:
      ls[int(i[0])] = i[1]
      ans += (i[1]*(i[1]-1)//2)

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

import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

def main():
	n=II()
	G=[]
	for _ in range(n):
		s=input().rstrip().decode()
		G.append(list(s*2))

	ans=0
	for x in range(n):
		f=1
		for i in range(n):
			if f==0:
				break
			for j in range(n):
				#print(i,j)
				if G[i][j]!=G[j-x][i+x]:
					f=0
					break
		else:
			#print(x)
			ans+=n
	print(ans)










if __name__ == "__main__":
	main()


### FIXED CODE ###

import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()

def main():
	n=II()
	G=[]
	for _ in range(n):
		s=input().rstrip().decode()
		G.append(list(s*2))

	ans=0
	for x in range(n):
		f=1
		for i in range(n):
			if f==0:
				break
			for j in range(n):
				#print(i,j)
				if G[i][j]!=G[j-x][i+x]:
					f=0
					break
		else:
			#print(x)
			ans+=n
	print(ans)










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

#ABC129-C
N,M=map(int,input().split())
a=[]
num=0 #N段までの行き方
check=0 #行けるかどうか
for i in range(M):
    a.append(int(input()))

for i in range(M-1):
    dif=a[i+1]-a[i]
    if dif==1:
        check=1
        break
        
f={}
f[0]=0 #番号を段数と一致させるため
if (1 in a)==True: #１が壊れているとき
    f[1]=0
else:
    f[1]=1
if (2 in a)==True: #２が壊れているとき
    f[2]=0
elif f[1]==0: #１が壊れているとき
    f[2]=1
else:
    f[2]=2

if check==0:
    for i in range(1,N-1): #1~N-2
        if any(i+2==a[k] for k in range(M)): #壊れている階段は、２段前に見つけておく。
            f[i+2]=0
            continue
        f[i+2]=f[i+1]+f[i]
    num=f[N]

#for i in range(101):
    #print(str(i)+":"+str(f[i]))
print(num%1000000007)

### FIXED CODE ###

#ABC129-C
N,M=map(int,input().split())
a=[]
broke={} #N段目が壊れているか
broke[0]=0
for i in range(1,N+1):
    broke[i]=0

f={}
f[0]=0 #番号を段数と一致させるため
num=0 #N段までの行き方
check=0 #行けるかどうか

for i in range(M):
    a.append(int(input()))
    n=a[i]
    broke[n]=1 #ｎ段目が壊れていることを記憶
    f[n]=0

for i in range(M-1): #壊れている階段同士の差が１の場所があるか調べる。
    dif=a[i+1]-a[i]
    if dif==1:
        check=1
        break
        
if (1 in a)==True: #１が壊れているとき
    f[1]=0
else:
    f[1]=1
if (2 in a)==True: #２が壊れているとき
    f[2]=0
elif f[1]==0: #１が壊れているとき
    f[2]=1
else:
    f[2]=2

if check==0:
    for i in range(1,N-1): #1~N-2
        if broke[i+2]==1:
            continue
        f[i+2]=f[i+1]+f[i]
    num=f[N]

#for i in range(N+1):
    #print(str(i)+":"+str(f[i]))
print(num%1000000007)
#print(broke)
### BUGGY CODE ###

s=input()
l=len(s)
mod=10**9+7
dp=[[0]*13 for i in range(l)]
if s[0]=="?":
  dp[0]=[1]*10+[0]*3
else:
  dp[0][int(s[0])]=1
for i in range(1,l):
  if s[i]=="?":
    for j in range(10):
      for k in range(13):
          dp[i][(10*k+j)%13]+=dp[i-1][k]%mod
  else:
    for k in range(13):          
      dp[i][(int(s[i])+10*k)%13]+=dp[i-1][k]%mod

print(dp[-1][5]%mod)

### FIXED CODE ###

s=input()
l=len(s)
mod=10**9+7
dp=[[0]*13 for i in range(l)]
if s[0]=="?":
  dp[0]=[1]*10+[0]*3
else:
  dp[0][int(s[0])]=1
for i in range(1,l):
  if s[i]=="?":
    for j in range(10):
      for k in range(13):
          dp[i][(10*k+j)%13]+=dp[i-1][k]%mod
  else:
    for k in range(13):          
      dp[i][(int(s[i])+10*k)%13]+=dp[i-1][k]%mod

print(dp[-1][5]%mod)
### BUGGY CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,k = LI()
    a = LI()
    r = [0] * n
    for i in range(1,n):
        t = r[i-1] + abs(a[i-1]-a[i])
        for j in range(2,min(i, k)+1):
            if t <= r[i-j]:
                continue
            u = r[i-j] + abs(a[i-j]-a[i])
            if t > u:
                t = u
        r[i] = t

    return r[-1]


print(main())


### FIXED CODE ###

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    n,k = LI()
    a = LI()
    r = [0] * n
    for i in range(1,n):
        ai = a[i]
        t = r[i-1] + abs(a[i-1]-ai)
        mj = i - k
        if mj < 0:
            mj = 0
        for j in range(mj,i-1):
            u = r[j] + abs(a[j]-ai)
            if t > u:
                t = u

        r[i] = t

    return r[-1]


print(main())
### BUGGY CODE ###

from sys import stdin
import sys
N=int(stdin.readline().rstrip())
data=[]
for i in range(N):
    data.append([int(x) for x in stdin.readline().rstrip().split()])
for X in range(0,101):
    for Y in range(0,101):
        for data_ in data:
            H = data_[2] + abs(X-data_[0]) + abs(Y-data_[1])
            flag = True
            for data__ in data:
                if max(H-abs(X-data__[0])-abs(Y-data__[1]),0) != data__[2]:
                    flag = False
            if flag:
                break
        else:
            continue
        break
    else:
        continue
    break
    
print(X,Y,H)

### FIXED CODE ###

from sys import stdin
import sys
N=int(stdin.readline().rstrip())
data=[]
for i in range(N):
    data.append([int(x) for x in stdin.readline().rstrip().split()])
for X in range(0,101):
    for Y in range(0,101):
        for data_ in data:
            H = data_[2] + abs(X-data_[0]) + abs(Y-data_[1])
            flag = True
            for data__ in data:
                if max(H-abs(X-data__[0])-abs(Y-data__[1]),0) != data__[2]:
                    flag = False
            if flag:
                break
        else:
            continue
        break
    else:
        continue
    break
    
print(X,Y,H)
### BUGGY CODE ###

import numpy as np
S = input()
mod = 10 ** 9 + 7

n = len(S)
a = S[-1]
dp = np.zeros((n, 26), int)
x_ = dp[0]
l = [[(13 - i * j % 13, 26 - i * j % 13) for j in range(0, 10)] for i in [1, 10, 9, 12, 3, 4]] * (n // 6 + 1)
if a == "?":
    x_[0:10] += 1
else:
    x_[int(a)] += 1
x_[13:] = x_[:13]
for s, x, l_ in zip(S[-2::-1], dp[1:], l[1:]):
    if s == "?":
        x[:13] += sum([x_[v[0]:v[1]] for v in l_])
    else:
        v = l_[int(s)]
        x[:13] += x_[v[0]:v[1]]
    x %= mod
    x[13:] = x[:13]
    x_ = x
print(x_[5])

### FIXED CODE ###

#!python3

LI = lambda: list(map(int, input().split()))

# input
S = input()

MOD = 10 ** 9 + 7


def main():
    n = len(S)
    m = 5
    w = []
    p = 1
    for i in range(n):
        s = S[-1 - i]
        if s == "?":
            w.append(p)
        else:
            m = (m - int(s) * p) % 13
        p = p * 10 % 13

    n = len(w)
    l1 = [0] * 13
    l1[0] = 1
    for i in range(1, n + 1):
        l2 = [0] * 13
        for j in range(10):
            x = w[i - 1] * j % 13
            for k in range(13):
                t = (x + k) % 13
                l2[t] += l1[k]
        l1 = [y % MOD for y in l2]
    
    ans = l1[m]
    print(ans)


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

r, g, b, n = map(int, input().split())

li = [r, g, b]
li.sort(reverse=True)

num_max_0 = n//li[0]
num_max_1 = n//li[1]

ans = 0
for num_0 in range(num_max_0 + 1):
    for num_1 in range(num_max_1 + 1):
        ball_01 = num_0*li[0] + num_1*li[1]
        ball_2 = n - ball_01
        
        if ball_2 >= 0 and ball_2 % li[2] == 0:
            ans += 1

print(ans)

### FIXED CODE ###

r, g, b, n = map(int, input().split())

num_max_r = n//r

ans = 0
for num_r in range(num_max_r + 1):
    
    n_r = n - num_r*r
    num_max_g = n_r//g
    
    for num_g in range(num_max_g + 1):
        n_r_g = n_r - num_g*g
        
        if n_r_g >= 0 and n_r_g % b == 0:
            ans += 1

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

n, m, d = map(int, input().split())
sum = 0
patt = (n-d)
if d != 0:
    patt = 2 * patt
beau = n ** (m-2) * (m-1)
print(patt * beau / (n**m))

### FIXED CODE ###

n, m, d = map(int, input().split())
sum = 0
patt = n-d
if d != 0:
    patt = 2 * patt
print(patt * (m-1) / (n * n))
### BUGGY CODE ###

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

def fact(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])
    if arr==[]:
        arr.append([n, 1])
    return arr

from collections import defaultdict
cntd=defaultdict(int)
for i in range(len(a)):
    lis = fact(a[i])
    for num,cnt in lis:
        if num==1:
            continue
        cntd[num]+=1

flg=False
for c in cntd.values():
    if c==n:
        print("not coprime")
        exit()
    if c>1:
        flg=True
if flg:
    print("setwise coprime")
else:
    print("pairwise coprime")

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
M=max(a)
biggest_prime = [0] * (M+10)
for i in range(2, M+10):
    if biggest_prime[i] == 0:
        biggest_prime[i] = i
        for j in range(i*i, M+1, i):
            biggest_prime[j] = i

from collections import defaultdict
cntd=defaultdict(int)
for i in range(len(a)):
    num = a[i]
    while num>1:
        p=biggest_prime[num]
        cntd[p]+=1
        while num % p == 0:
            num//=p

flg=False
for c in cntd.values():
    if c==n:
        print("not coprime")
        exit()
    if c>1:
        flg=True
if flg:
    print("setwise coprime")
else:
    print("pairwise coprime")
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10 ** 6)  # 再帰関数の再帰の深さを設定
to_index = lambda x: int(x) - 1  # 入力した数字に1を引いたものを返す
print_list_in_2D = lambda x: print(*x, sep="\n")  # リストの要素を改行を挟んで表示する関数

# 入力を整数に変換して受け取る
def input_int():
    return int(input())

II = input_int

def map_int_input():
    return map(int, input())

MII = map_int_input

def MII_split():
    return map(int, input().split())

def MII_to_index():
    return map(to_index, input())

def MII_split_to_index():
    return map(to_index, input().split())

# 入力全てを整数に変換したものの配列を受け取る
def list_int_inputs():
    return list(map(int, input()))

LII = list_int_inputs

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

# 2次元リスト化
def LII_2D(rows_number):
    return [LII() for _ in range(rows_number)]

def LII_split_2D(rows_number):
    return [LII_split() for _ in range(rows_number)]

S = input()
N = len(S)
# N 文字の文字列 S から、長さ N+1 の ---累積和--- s[0], s[1], ..., s[N] を作る
# これを 2019 で割ったあまりで分類する (具体的には counter[ r ] := あまりが r のやつが何個あるか)
# 各 r ごとに、counter[r] 個から 2 個選ぶ方法の数を、足し上げる

counter = [0] * 2019

for i in range(N + 1):
    if i == 0:
        sub = 0
    elif i == 1:
        sub = int(S[N - 1])
    else:
        sub = int(S[N - i] + str(sub))
    rest = sub % 2019
    counter[rest] += 1
    # if rest in counter:  # dict を使い検索することで，O(N)の余剰
    #     counter[rest] += 1
    # else:
    #     counter[rest] = 1


# def combinations_count(n, r):
#     return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

ans = 0
for r in counter:
    ans += r * (r - 1) / 2
print(int(ans))

### FIXED CODE ###

S = list(input())
N = len(S)
# N 文字の文字列 S から、長さ N+1 の ---累積和--- s[0], s[1], ..., s[N] を作る
# これを 2019 で割ったあまりで分類する (具体的には counter[ r ] := あまりが r のやつが何個あるか)
# 各 r ごとに、counter[r] 個から 2 個選ぶ方法の数を、足し上げる

counter = [0] * 2019
k = 10
for i in range(N + 1):
    if i == 0:
        sub = 0
    elif i == 1:
        sub = int(S[N - 1])
    else:
        sub += int(S[N - i]) * k
        k *= 10
        k %= 2019
    rest = sub % 2019
    counter[rest] += 1

ans = 0
for r in counter:
    ans += r * (r - 1) // 2
print(ans)
### BUGGY CODE ###

from collections import deque
from itertools import product


def bfs():
    while q:
        i, j = q.popleft()
        for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
            ni, nj = i + di, j + dj
            if not (0 <= ni < H and 0 <= nj < W and dist[ni][nj] < 0):
                continue
            dist[ni][nj] = dist[i][j] + 1
            q.append((ni, nj))


H, W = map(int, input().split())
A = [input() for _ in range(H)]

q = deque()
dist = [[-1] * W for _ in range(H)]
for i, j in product(range(H), range(W)):
    if A[i][j] == ".":
        continue
    q.append((i, j))
    dist[i][j] = 0
bfs()
print(max(max(row) for row in dist))


### FIXED CODE ###

from collections import deque


def bfs(q):
    ans = 0
    while q:
        i, j = q.popleft()
        for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            ni, nj = i + di, j + dj
            if 0 <= ni < H and 0 <= nj < W and dist[ni][nj] < 0:
                q.append((ni, nj))
                dist[ni][nj] = dist[i][j] + 1
                ans = max(ans, dist[ni][nj])
    return ans


H, W = map(int, input().split())
field = [input() for _ in range(H)]
dist = [[-1] * W for _ in range(H)]
q = deque()
for i in range(H):
    for j in range(W):
        if field[i][j] == "#":
            dist[i][j] = 0
            q.append((i, j))
print(bfs(q))
### BUGGY CODE ###

from array import array
n = int(input())
a_list = [int(input()) for _ in range(n)]
max_num = max(array('L',a_list))
for i in range(len(a_list)):
    if a_list[i] != max_num:
        print(max_num)
    else:
        print(max(array('L',a_list[:i]+a_list[i+1:])))

### FIXED CODE ###

import heapq
n = int(input())
a_list = [int(input()) for _ in range(n)]
a_list_heap = list(map(lambda x:(-1)*x,a_list))
heapq.heapify(a_list_heap)
max_num = a_list_heap[0]*(-1)

for i in range(len(a_list)):
    if a_list[i] != max_num:
        print(max_num)
    else:
        tmp = heapq.heappop(a_list_heap)
        print(a_list_heap[0]*(-1))
        heapq.heappush(a_list_heap,tmp)