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

N=int(input())
a=list(map(int,input().split()))
a_=sorted(a)
ans=0
while len(a_)>1:#1になった時点で終わり。
    x,y=0,0
    for n in range(a_[-1]):
        if a_[-1]<=2**n:
            t=n
            break
    if 2**t==a_[-1]:
    #これは、2,4,8とか2のべき乗だけが引っかかる条件
        if a_[-1]==a_[-2]:
        #2のべきでも、きちんと2個存在するならおｋ
            a_.pop()
            a_.pop()
            ans+=1
        else:
            a_.pop()
    else:
        x+=a_[-1]
        y+=2**t-a_[-1]
        #inが遅すぎるかもしれない。ちょっと高速化
        #上で被りうる奴は排除できている。
        for j in range(1,len(a_)+1):
            if y==a_[-j]:
                ans+=1
                a_.pop(-j)
                a_.pop()
                break
            elif y<a_[-j]:#常に下回るときを考慮できていなかった
                if j==len(a_):
                    a_.pop()
            else:
                a_.pop()
                break
        
                #可能性なしがわかったらすぐ切る！！
print(ans)
#removeって探して削除なので遅い。popに変更してみよう
#forにしたことでインデックスも取得できるので。

### FIXED CODE ###

from collections import Counter
n = int(input())
a = list(map(int, input().split()))
a.sort(reverse=True)
c = Counter(a)

ans = 0
for i in a:
    if c[i] == 0:
        continue
    c[i] -= 1
    k = 1<<i.bit_length()
    j = k-i
    if j in c and c[j] > 0:
        ans += 1
        c[j] -= 1
print(ans)
### BUGGY CODE ###

K, S = map(int, input().split())
cnt = 0
for i in range(K + 1):
  for j in range(i, K + 1):
    for k in  range(j, K + 1):
      if i + j + k == S:
        if i == j == k:
          cnt += 1
        elif i == j or j == k or i == k:
          cnt += 3
        else:
          cnt += 6
print(cnt)

### FIXED CODE ###

K, S = map(int, input().split())
cnt = 0
for i in range(K + 1):
  for j in range(K + 1):
    if S >= i + j >= S - K:
      cnt += 1
print(cnt)
### BUGGY CODE ###

N = int(input())
H = list(map(lambda x:int(x), input().split()))

idx = sorted(range(N-1), key=lambda k: H[k], reverse=True)

ans = 0
for i in idx:
  count = 0
  if (i != 0) and (H[i-1] > H[i]): continue
#  if i == N-1: continue

  j = i
  while j < N-1:
    if H[j] < H[j+1]: break
    count += 1
    j += 1
  ans = max(ans, count)

print(ans)


### FIXED CODE ###

N = int(input())
H = list(map(lambda x:int(x), input().split()))
count = 0
ans = 0
for i in range(N-1):
  if H[i] >= H[i+1]:
    count += 1
  else:
    count = 0
  ans = max(ans, count)

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

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
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 list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
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 pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def main():
    n = I()
    a = LI()
    b = LI()

    def f(a,b,n):
        c = sorted([(ai,bi) for ai,bi in zip(a,b) if ai < bi], reverse=True)
        if len(c) == 0:
            return n
        if len(c) == 1:
            return n % c[0][0] + n // c[0][0] * c[0][1]

        a = [_[0] for _ in c]
        b = [_[1] for _ in c]
        r = n
        for i in range(0,n+1,a[0]):
            t = i // a[0] * b[0] + f(a[1:], b[1:], n-i)
            if r < t:
                r = t
        return r

    t = f(a,b,n)
    r = f(b,a,t)

    return r


print(main())



### FIXED CODE ###

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

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
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 list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
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 pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)

def main():
    n = I()
    a = LI()
    b = LI()

    def f(c,n):
        c0 = c[0]
        if len(c) == 1:
            return n % c0[0] + n // c0[0] * c0[1]

        r = n
        for i in range(0,n+1,c0[0]):
            t = i // c0[0] * c0[1] + f(c[1:], n-i)
            if r < t:
                r = t
        return r

    c = sorted([(ai,bi) for ai,bi in zip(a,b) if ai < bi], reverse=True)
    t = n
    if len(c) > 0:
        t = f(c,n)

    d = sorted([(ai,bi) for ai,bi in zip(b,a) if ai < bi], reverse=True)
    r = t
    if len(d) > 0:
        r = f(d,t)

    return r


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

import itertools

n = int(input())
s = list(input())
ans = 0

for i in range(0,10):
    for j in range(0,10):
        for k in range(0,10):
            flag1 = 0
            flag2 = 0
            flag3 = 0
            for m in range(n):
                if flag1 == 0:
                    if int(s[m]) == i:
                        flag1 = 1
                elif flag2 == 0:
                    if int(s[m]) == j:
                        flag2 = 1
                elif flag3 == 0:
                    if int(s[m]) == k:
                        flag3 = 1
                        ans += 1
                        break
                    
print(ans)

### FIXED CODE ###

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

li = [[] for _ in range(10)]

for i in range(n):
    t = int(s[i])
    li[t].append(i)

a = 0
b = 0
c = 0
cnt = 0

for i in range(10):
  for j in range(10):
    for k in range(10):
      b = 0
      a = 0
      
      if len(li[i]) > 0:
        a = li[i][0]
          
        for d in li[j]:
            if d > a:
                b = d
                break
        else:
            break
        
        for e in li[k]:
            if e > b:
                cnt += 1
                break
        

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

K,S = map(int, input().split())

ans = 0
for x in range(K+1):
  for y in range(K+1):
    for z in range(K+1):
      if x+y+z == S:
        ans +=1

print(ans)

### FIXED CODE ###

K,S = map(int, input().split())

ans = 0
if K*3<S:
  print(0)
  exit()

for x in range(K, -1, -1):
  if x >S:
    continue
  for y in range(min(S-x, K), -1, -1):
    if x+y >S:
      continue
    for z in range(min(S-x-y, K), -1, -1):
      if x+y+z==S:
        ans+=1
      elif x+y+z<S:
        break

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

from collections import defaultdict


def longest_common_subsequence(s, t):
    dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]
    for i in range(len(s)):
        for j in range(len(t)):
            if s[i] == t[j]:
                dp[i + 1][j + 1] = dp[i][j] + 1
            else:
                dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
    return dp[-1][-1]


def longest_common_subsequence2(s, t):
    dp = [0] * (len(t) + 1)
    for i in range(len(s)):
        tmp = dp[:]
        for j in range(len(t)):
            if s[i] == t[j]:
                dp[j + 1] = tmp[j] + 1
            elif dp[j + 1] < dp[j]:
                dp[j + 1] = dp[j]
    return dp[-1]


def main():
    n = int(input())
    for _ in range(n):
        X, Y = input(), input()
        print(longest_common_subsequence2(X, Y))


if __name__ == '__main__':
    main()

### FIXED CODE ###

from collections import defaultdict


def longest_common_subsequence(s, t):
    dp = [[0] * (len(t) + 1) for _ in range(len(s) + 1)]
    for i in range(len(s)):
        for j in range(len(t)):
            if s[i] == t[j]:
                dp[i + 1][j + 1] = dp[i][j] + 1
            else:
                dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
    return dp[-1][-1]


def longest_common_subsequence2(s, t):
    dp = [0] * (len(t) + 1)
    for i in range(len(s)):
        si = s[i]
        tmp = dp[:]
        for j in range(len(t)):
            if si == t[j]:
                dp[j + 1] = tmp[j] + 1
            elif dp[j + 1] < dp[j]:
                dp[j + 1] = dp[j]
    return dp[-1]


def main():
    n = int(input())
    for _ in range(n):
        X, Y = input(), input()
        print(longest_common_subsequence2(X, Y))


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

N = int(input())
S = input()

#S = "RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB"

Slist = list(S)

count = 0
for i in range(len(Slist)):
    for j in range(i+1, len(Slist)):
        #if(Slist[i] == Slist[j]):
        #    break
        for k in range(j+1, len(Slist)):
            notEqualColor = (Slist[i] == Slist[j] or Slist[j] == Slist[k] or Slist[k] == Slist[i])
            notEqualDistance = (j - i == k - j)

            if((notEqualColor or notEqualDistance) == False):
                count += 1

print(count)


### FIXED CODE ###

import collections

N = int(input())
S = input()

CountRGB = collections.Counter(S)

ans = CountRGB["R"] * CountRGB["G"] * CountRGB["B"]

tmp = 0
for i in range(N-2):
    for j in range(i+1, N-1):

        if(2 * j - i > N - 1):
            break

        checker = []
        checker.append(S[i])
        checker.append(S[j])
        checker.append(S[2 * j - i])

        c = collections.Counter(checker)

        if(c["R"] == 1 and c["G"] == 1 and c["B"] == 1):
            tmp +=1

print(ans - tmp)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(1000000000)
import math
from fractions import gcd
def lcm(a, b): return a * b // gcd(a, b)
from itertools import count, permutations
from functools import lru_cache
from collections import deque, defaultdict
from pprint import pprint
ii = lambda: int(input())
mis = lambda: map(int, input().split())
lmis = lambda: list(mis())
INF = float('inf')
N1097 = 10**9 + 7

def meg(f, ok, ng):
    while abs(ok-ng)>1:
        mid = (ok+ng)//2
        if f(mid):
            ok=mid
        else:
            ng=mid
    return ok

def get_inv(n, modp):
    return pow(n, modp-2, modp)

def factorials_list(n, modp):    # 10**6
    fs = [1]
    for i in range(1, n+1):
        fs.append(fs[-1] * i % modp)
    return fs

def invs_list(n, fs, modp):     # 10**6
    invs = [get_inv(fs[-1], modp)]
    for i in range(n, 1-1, -1):
        invs.append(invs[-1] * i % modp)
    invs.reverse()
    return invs

def comb(n, k, modp):
    num = 1
    for i in range(n, n-k, -1):
        num = num * i % modp
    den = 1
    for i in range(2, k+1):
        den = den * i % modp
    return num * get_inv(den, modp) % modp

def comb_from_list(n, k, modp, fs, invs):   
    return fs[n] * invs[n-k] * invs[k] % modp

#

class UnionFindEx:
    def __init__(self, size):
        #正なら根の番号、負ならグループサイズ
        self.roots = [-1] * size
    def getRootID(self, i):
        r = self.roots[i]
        if r < 0:   #負なら根
            return i
        else:
            r = self.getRootID(r)
            self.roots[i] = r
            return r
    def getGroupSize(self, i):
        return -self.roots[self.getRootID(i)]
    def connect(self, i, j):
        r1, r2 = self.getRootID(i), self.getRootID(j)
        if r1 == r2:
            return False
        if self.getGroupSize(r1) < self.getGroupSize(r2):
            r1, r2 = r2, r1
        self.roots[r1] += self.roots[r2]    #サイズ更新
        self.roots[r2] = r1
        return True

Yes = 'Yes'
No = 'No'

def main():
    X,Y,R,G,B=mis()
    rs=lmis()
    rs.sort(reverse=True)
    gs=lmis()
    gs.sort(reverse=True)
    bs=lmis()
    bs.sort(reverse=True)
    def get_score(red_paint):
        if red_paint > B:
            return INF
        if Y > G + (B - red_paint):
            return INF
        ans = 0
        ans += sum(bs[:red_paint])
        ans += sum(rs[:X - red_paint])
        gi = 0
        bi = red_paint
        for _ in range(Y):
            if G == gi:
                go_g = False
            elif B == bi:
                go_g = True
            else:
                go_g = (gs[gi] >= bs[bi])
            if go_g:
                ans += gs[gi]
                gi += 1
            else:
                ans += bs[bi]
                bi += 1
        return ans
    print(max(get_score(i) for i in range(X+1)))


main()







### FIXED CODE ###

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

def main():
    X, Y, A, B, C = mis()
    p = sorted(lmis(), reverse=True)[:X]
    q = sorted(lmis(), reverse=True)[:Y]
    r = lmis()
    print(sum(sorted(p+q+r, reverse=True)[:X+Y]))

main()
### BUGGY CODE ###

N = int(input())
A = list(map(int, input().split()))

T = 1
for i in A:
    T = T * i
if T > 10 ** 18:
    print(-1)
else:
    print(T)


### FIXED CODE ###

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

a = 1
if 0 in list:
    print(0)
    exit()
else:
    for i in list:
        a *= i
        if a > 10**18:
            print(-1)
            exit()
print(a)
### BUGGY CODE ###

#!/usr/bin/env python3
n = int(input()) 
A = list(map(str, input().split()))
q = int(input()) 
for i in range(q):
    b, c = map(str, input().split())
    A = [int(str(a).replace(b, c)) for a in A]
    print(sum(A))

### FIXED CODE ###

#!/usr/bin/env python3
from collections import Counter
N = int(input())
A = list(map(int, input().split()))
d = Counter(A)
Q = int(input())
ans = sum(A)
for i in range(Q):
    b, c = map(int, input().split())
    ans += (c-b) * d[b]
    d[c] += d[b]
    d[b] = 0
    print(ans)
### BUGGY CODE ###

import re
X = raw_input()
iter = 100000
pat = re.compile('(ST)')

for i in xrange(iter):
    s =	pat.search(X)
    if s is	not None:
    	X =	X.replace('ST','',1)
    else:
	pass
print len(X)

### FIXED CODE ###

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

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 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 main():
    x = S()
    s_cnt = 0
    removed = 0
    for c in x:
        if c == 'S':
            s_cnt += 1
        if c == 'T':
            if s_cnt > 0:
                s_cnt -= 1
                removed += 2
    print(len(x) - removed)
main()
### BUGGY CODE ###

n = int(input())

ans = 0
for i in range(n):
    ans += i

print(ans)


### FIXED CODE ###

n = int(input())

print(n * (n - 1) // 2)
### BUGGY CODE ###

#!/usr/bin/env python3
from collections import Counter
import sys

try:
    from typing import Set
except ImportError:
    pass


def f(s: "Set[str]", p: int, i: int):
    bins = Counter(sj[p:p + 1] for sj in s)
    cum = 0
    key = ""
    cnt = 0
    for key, cnt in sorted(bins.items()):
        cum += cnt
        if cum > i:
            break
    else:
        raise IndexError(i)
    new_s = {sj for sj in s if sj[p:p + 1] == key}
    if len(new_s) == 1:
        return list(new_s)[0]
    return f(new_s, p + 1, i - cum + cnt)


def solve(s: str, K: int):
    n = len(s)
    ss = {
        s[i:j]
        for i in range(n)
        for j in range(i + 1, n + 1)
    }
    print(f(ss, 0, K - 1))


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    K = int(next(tokens))  # type: int
    solve(s, K)


if __name__ == '__main__':
    main()


### FIXED CODE ###

#!/usr/bin/env python3
import sys


def solve(s: str, K: int):
    n = len(s)
    ss = {
        s[i:j]
        for i in range(n)
        for j in range(i + 1, min(n + 1, i + K + 1))
    }
    print(sorted(ss)[K - 1])
 

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    K = int(next(tokens))  # type: int
    solve(s, K)


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

H, W, M = map(int,input().split())

X = [0] * H
Y = [0] * W

B = []
h = H
while h:
    h -= 1
    B.append([])
    
A = []
m = M
while m:
    m -= 1
    x, y = map(int,input().split())
    x, y = x -1, y -1
    A.append((x, y))
    B[x].append(y)
    X[x] += 1
    Y[y] += 1

def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]

xm = max(X)
ym = max(Y)
xms = my_index_multi(X, xm)
yms = my_index_multi(Y, ym)

z = 0
for a, b in A:
    if a in xms:
        if b in yms: z += 1
if z == len(xms) * len(yms):
    ans = False
else:
    ans = True

cnt = xm + ym         
print(cnt if ans else cnt - 1)

### FIXED CODE ###

import sys

input = sys.stdin.readline
H, W, M = map(int,input().split())
q=set(tuple(map(lambda x :int(x)-1,input().split())) for _ in range(M))

X = [0] * H
Y = [0] * W

for i, j in q:
    X[i] += 1
    Y[j] += 1
    
def my_index_multi(l, x):
    return [i for i, _x in enumerate(l) if _x == x]

xm = max(X)
ym = max(Y)
xms = my_index_multi(X, xm)
yms = my_index_multi(Y, ym)

ans = xm + ym - 1

bl = False
for i in xms:
    for j in yms:
        if not (i, j) in q:
            print(ans + 1)
            sys.exit()
            bl = True
            
print(ans)
### BUGGY CODE ###

n = int(input())
a = [int(input()) for _ in range(n)]
for i in range(n):
    print(max(a[:i] + a[i+1:]))

### FIXED CODE ###

import numpy as np

n = int(input())
a = [int(input()) for _ in range(n)]
na = np.array(a)
maxI = np.argmax(na)
maxA = na[maxI]
nb = np.copy(na)
nb[maxI] = 0
maxA2 = np.max(nb)
for i in range(n):
    if i != maxI:
        print(na[maxI])
    else:
       print(maxA2)
### BUGGY CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w = list(map(int, input().split()))
a = [None]*h
for i in range(h):
    a[i] = input()
    if "S" in a[i]:
        start = (i*w+a[i].index("S"))
    if "T" in a[i]:
        goal = (i*w+a[i].index("T"))
if start%w==goal%w or start//w==goal//w:
    val = -1
else:
    import networkx as nx
    g = nx.DiGraph()
    for i in range(2*h*w):
        g.add_node(i)
    for i in range(h*w):
#         if i not in (start, goal):
        g.add_edge(2*i, 2*i+1, capacity=1)
    start = start*2+1
    goal = goal*2
    def add(i0,j0,i1,j1):
        u = i0*w+j0
        v = i1*w+j1
        g.add_edge(2*u+1, 2*v, capacity=1)
        g.add_edge(2*v+1, 2*u, capacity=1)
    for i in range(h):
        index = []
        for j in range(w):
            if a[i][j] in ("o", "S", "T"):
                index.append(j)
        for x in index:
            for y in index:
                if x!=y:
                    add(i,x,i,y)
    for j in range(w):
        index = []
        for i in range(h):
            if a[i][j] in ("o", "S", "T"):
                index.append(i)
        for x in index:
            for y in index:
                if x!=y:
                    add(x,j,y,j)
    val = nx.maximum_flow(g, start, goal)[0]
print(val)

### FIXED CODE ###

import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w = list(map(int, input().split()))
data= []
rs = []
cs = []
for i in range(h):
    c = input()
    if "S" in c:
        start = (i, c.index("S"))
    if "T" in c:
        goal = (i, c.index("T"))
    for j in range(w):
        if c[j] in ("o"):#, "S", "T"):
            data.append(1)
            rs.append(i)
            cs.append(h+j)
            data.append(1)
            rs.append(h+j)
            cs.append(i)
s = h+w
t = h+w+1
V = 10**9
data.append(V)
rs.append(s)
cs.append(start[0])
data.append(V)
rs.append(start[0])
cs.append(s)

data.append(V)
rs.append(s)
cs.append(start[1]+h)
data.append(V)
rs.append(start[1]+h)
cs.append(s)

data.append(V)
rs.append(goal[0])
cs.append(t)
data.append(V)
rs.append(t)
cs.append(goal[0])

data.append(V)
rs.append(t)
cs.append(goal[1]+h)
data.append(V)
rs.append(goal[1]+h)
cs.append(t)

import scipy.sparse
m = scipy.sparse.csr_matrix((data, (rs, cs)), shape=(h+w+2,h+w+2))
val = scipy.sparse.csgraph.maximum_flow(m, s, t).flow_value
if val>=10**9:
    val = -1
print(val)
### BUGGY CODE ###

L = list(input())
N = [-1 for i in range(len(L)+1)]

def sounyu(L,N):    
    for i in range(len(N)-1):
        if L[i] == '<':
            N[i] = max(N[i],0)
            while(L[i] == '<'):
                N[i+1] = max(N[i+1],N[i]+1)
                i += 1
                if i == len(L):
                    break

sounyu(L,N)
L.reverse()
for l in range(len(L)):
    if L[l] == '>':
        L[l] = '<'
    else:
        L[l] = '>'
N.reverse()
sounyu(L,N)

print(sum(N))



### FIXED CODE ###

L = input()
L = list(L.split('><'))
if len(L) == 1:
    a = [L[0].count('<'),L[0].count('>')]
    a_max = max(a)
    ans = a_max*(a_max+1)/2
else:
    ans = 0
    for i in range(len(L)):
        if i == 0:
            a = [L[i].count('<'),L[i].count('>')+1]
        elif i == len(L)-1:
            a = [L[i].count('<')+1,L[i].count('>')]
        else:
            a = [L[i].count('<')+1,L[i].count('>')+1]
        a_max = max(a)
        a_min = min(a)

        ans += a_max*(a_max+1)/2
        ans += a_min*(a_min-1)/2

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

H,W = map(int,input().split())
Ch, Cw = map(lambda x: int(x)-1,input().split())
Dh, Dw = map(lambda x: int(x)-1,input().split())
S = []
for i in range(H):
  S.append(input())


from collections import deque

def bfs(sh,sw):
  queue = deque([(sh,sw)])
  d = [[None]*W for _ in range(H)]
  now = set()
  d[sh][sw]=0
  
  while queue:
    h,w = queue.popleft()
    now.add((h,w))
    for nh,nw in [(h-1,w),(h+1,w),(h,w-1),(h,w+1)]:
      if (0<=nh<=H-1 and 0<=nw<=W-1 and S[nh][nw] == '.' and d[nh][nw] is None) == False: continue
      queue.append((nh,nw))
      now.add((nh,nw))
      d[nh][nw]=d[h][w]

    if queue: continue
    for h,w in now:      
      for i in range(-2,3):
        for j in range(-2,3):
          if i==0 and abs(j)<=1: continue
          if j == 0 and abs(i)<=1: continue
          nh,nw = h-i,w-j
          if (0<=nh<=H-1 and 0<=nw<=W-1 and S[nh][nw] == '.' and d[nh][nw] is None) == False: continue
          d[nh][nw] = d[h][w]+1
          queue.append((nh,nw))
    #print(queue)
  return d

d = bfs(Ch,Cw)
if d[Dh][Dw] == None: 
  print(-1)
  exit()
print(d[Dh][Dw])

### FIXED CODE ###

H,W = map(int,input().split())
Ch, Cw = map(lambda x: int(x)-1,input().split())
Dh, Dw = map(lambda x: int(x)-1,input().split())
S = []
for i in range(H):
  S.append(input())


from collections import deque

def bfs(sh,sw):
  queue = deque([(sh,sw)])
  d = [[None]*W for _ in range(H)]
  now = set()
  d[sh][sw]=0
  
  while queue:
    h,w = queue.popleft()
    now.add((h,w))
    for nh,nw in [(h-1,w),(h+1,w),(h,w-1),(h,w+1)]:
      if (0<=nh<=H-1 and 0<=nw<=W-1 and S[nh][nw] == '.' and d[nh][nw] is None) == False: continue
      queue.append((nh,nw))
      now.add((nh,nw))
      d[nh][nw]=d[h][w]

    if queue: continue
    for h,w in now:
      for i in range(-2,3):
        for j in range(-2,3):
          if i==0 and abs(j)<=1: continue
          if j == 0 and abs(i)<=1: continue
          nh,nw = h-i,w-j
          if (0<=nh<=H-1 and 0<=nw<=W-1 and S[nh][nw] == '.' and d[nh][nw] is None) == False: continue
          d[nh][nw] = d[h][w]+1
          queue.append((nh,nw))
    now = set()
    #print(queue)
  return d

d = bfs(Ch,Cw)
if d[Dh][Dw] == None: 
  print(-1)
  exit()
print(d[Dh][Dw])