Input:
# https://atcoder.jp/contests/dp/tasks/dp_l

'''

dp[i,j] ... dequeに[i,j]が残っているときに行動するプレイヤーのスコアの最大

dp[i,j] = max(a[i-1]-dp[i-1,j], a[j+1]-dp[i,j+1]) #これじゃgreedyと同じじゃん

dp[i,j] ... dequeに[i,j)が残っているときにその状態からスタートするプレイヤーが達成できるスコアの最大 (区間を伸ばしていく感じ)

初期値 dp[i,i]==0

dp[i,j]=max(a[i]-dp[i+1,j], a[j-1]-dp[i,j-1])

'''

import sys

sys.setrecursionlimit(1 << 25)

readline = sys.stdin.buffer.readline

read = sys.stdin.readline  # 文字列読み込む時はこっち

import numpy as np

from functools import partial

array = partial(np.array, dtype=np.int64)

zeros = partial(np.zeros, dtype=np.int64)

full = partial(np.full, dtype=np.int64)

def a_int(): return int(readline())

def ints(): return np.fromstring(readline(), sep=' ', dtype=np.int64)

MOD = 10**9 + 7

INF = 2**31  # 2147483648 > 10**9

# default import

N = a_int()

A = ints()

from numba import njit

@njit('(i8,i8[:])', cache=True)

def solve(N, A):

    dp = np.zeros((N + 1, N + 1), dtype=np.int64)

    for i in range(N - 1, -1, -1):

        for j in range(i + 1, N + 1):

            dp[i, j] = max(A[i] - dp[i + 1, j], A[j - 1] - dp[i, j - 1])

    print((dp[0, N]))

    # print(*dp, sep='\n')

solve(N, A)

# https://atcoder.jp/contests/dp/tasks/dp_l

'''

dp[i,j] ... dequeに[i,j]が残っているときに行動するプレイヤーのスコアの最大

dp[i,j] = max(a[i-1]-dp[i-1,j], a[j+1]-dp[i,j+1]) #これじゃgreedyと同じじゃん

dp[i,j] ... dequeに[i,j)が残っているときにその状態からスタートするプレイヤーが達成できるスコアの最大 (区間を伸ばしていく感じ)

初期値 dp[i,i]==0

dp[i,j]=max(a[i]-dp[i+1,j], a[j-1]-dp[i,j-1])

'''

import sys

sys.setrecursionlimit(1 << 25)

readline = sys.stdin.buffer.readline

read = sys.stdin.readline  # 文字列読み込む時はこっち

import numpy as np

from functools import partial

array = partial(np.array, dtype=np.int64)

zeros = partial(np.zeros, dtype=np.int64)

full = partial(np.full, dtype=np.int64)

def a_int(): return int(readline())

def ints(): return np.fromstring(readline(), sep=' ', dtype=np.int64)

MOD = 10**9 + 7

INF = 2**31  # 2147483648 > 10**9

# default import

N = a_int()

A = ints()

dp = zeros((N + 1, N + 1))

from numba import njit

@njit('(i8,i8[:],i8[:,:])', cache=True)

def solve(N, A, dp):

    for i in range(N - 1, -1, -1):

        for j in range(i + 1, N + 1):

            dp[i, j] = max(A[i] - dp[i + 1, j], A[j - 1] - dp[i, j - 1])

    print((dp[0, N]))

    # print(*dp, sep='\n')

solve(N, A, dp)

# https://atcoder.jp/contests/dp/tasks/dp_l
"""
dp[i,j] ... dequeに[i,j]が残っているときに行動するプレイヤーのスコアの最大
dp[i,j] = max(a[i-1]-dp[i-1,j], a[j+1]-dp[i,j+1]) #これじゃgreedyと同じじゃん
dp[i,j] ... dequeに[i,j)が残っているときにその状態からスタートするプレイヤーが達成できるスコアの最大 (区間を伸ばしていく感じ)
初期値 dp[i,i]==0
dp[i,j]=max(a[i]-dp[i+1,j], a[j-1]-dp[i,j-1])
"""
import sys

sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
import numpy as np
from functools import partial

array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

def a_int():
    return int(readline())

def ints():
    return np.fromstring(readline(), sep=" ", dtype=np.int64)

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
N = a_int()
A = ints()
from numba import njit

@njit("(i8,i8[:])", cache=True)
def solve(N, A):
    dp = np.zeros((N + 1, N + 1), dtype=np.int64)
    for i in range(N - 1, -1, -1):
        for j in range(i + 1, N + 1):
            dp[i, j] = max(A[i] - dp[i + 1, j], A[j - 1] - dp[i, j - 1])
    print((dp[0, N]))
    # print(*dp, sep='\n')

solve(N, A)

# https://atcoder.jp/contests/dp/tasks/dp_l
"""
dp[i,j] ... dequeに[i,j]が残っているときに行動するプレイヤーのスコアの最大
dp[i,j] = max(a[i-1]-dp[i-1,j], a[j+1]-dp[i,j+1]) #これじゃgreedyと同じじゃん
dp[i,j] ... dequeに[i,j)が残っているときにその状態からスタートするプレイヤーが達成できるスコアの最大 (区間を伸ばしていく感じ)
初期値 dp[i,i]==0
dp[i,j]=max(a[i]-dp[i+1,j], a[j-1]-dp[i,j-1])
"""
import sys

sys.setrecursionlimit(1 << 25)
readline = sys.stdin.buffer.readline
read = sys.stdin.readline  # 文字列読み込む時はこっち
import numpy as np
from functools import partial

array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

def a_int():
    return int(readline())

def ints():
    return np.fromstring(readline(), sep=" ", dtype=np.int64)

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import
N = a_int()
A = ints()
dp = zeros((N + 1, N + 1))
from numba import njit

@njit("(i8,i8[:],i8[:,:])", cache=True)
def solve(N, A, dp):
    for i in range(N - 1, -1, -1):
        for j in range(i + 1, N + 1):
            dp[i, j] = max(A[i] - dp[i + 1, j], A[j - 1] - dp[i, j - 1])
    print((dp[0, N]))
    # print(*dp, sep='\n')

solve(N, A, dp)

-    dp = np.zeros((N + 1, N + 1), dtype=np.int64)


Input:
from heapq import heapify, heappush, heappop

from heapq import _heapify_max, _heappop_max

import heapq

def _heappush_max(heap, item):

    heap.append(item)

    heapq._siftdown_max(heap, 0, len(heap)-1)

"""

method:

    heapify(x): ヒープに変換

    heappush(heap, item): itemをheapにpush

    heappop(heap): heapから最小値を取得 空の場合はIndexError

note:

    max heapにする場合は、prefix: _ とsuffix: _maxをつければ良い

"""

def main():

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

    h = [0] + list(map(int, input().split()))

    ans = [[] for _ in range(n+1)]

    for _ in range(m):

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

        _heappush_max(ans[a], h[b])

        _heappush_max(ans[b], h[a])

    out = 0

    for ai, hi in zip(ans[1:], h[1:]):

        if (not ai) or hi > _heappop_max(ai):

            out += 1

    print(out)

if __name__ == "__main__":

    main()

def main():

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

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

    to = [0]*(n+1)

    ans = 0

    for _ in range(m):

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

        to[a] = max(to[a], h[b-1])

        to[b] = max(to[b], h[a-1])

    for i, hi in enumerate(h, 1):

        t = to[i]

        if t == 0 or hi > t:

            ans += 1

    print(ans)

if __name__ == "__main__":

    main()

from heapq import heapify, heappush, heappop
from heapq import _heapify_max, _heappop_max
import heapq

def _heappush_max(heap, item):
    heap.append(item)
    heapq._siftdown_max(heap, 0, len(heap) - 1)

"""
method:
    heapify(x): ヒープに変換
    heappush(heap, item): itemをheapにpush
    heappop(heap): heapから最小値を取得 空の場合はIndexError
note:
    max heapにする場合は、prefix: _ とsuffix: _maxをつければ良い
"""

def main():
    n, m = list(map(int, input().split()))
    h = [0] + list(map(int, input().split()))
    ans = [[] for _ in range(n + 1)]
    for _ in range(m):
        a, b = list(map(int, input().split()))
        _heappush_max(ans[a], h[b])
        _heappush_max(ans[b], h[a])
    out = 0
    for ai, hi in zip(ans[1:], h[1:]):
        if (not ai) or hi > _heappop_max(ai):
            out += 1
    print(out)

if __name__ == "__main__":
    main()

def main():
    n, m = list(map(int, input().split()))
    h = list(map(int, input().split()))
    to = [0] * (n + 1)
    ans = 0
    for _ in range(m):
        a, b = list(map(int, input().split()))
        to[a] = max(to[a], h[b - 1])
        to[b] = max(to[b], h[a - 1])
    for i, hi in enumerate(h, 1):
        t = to[i]
        if t == 0 or hi > t:
            ans += 1
    print(ans)

if __name__ == "__main__":
    main()

-from heapq import heapify, heappush, heappop

-from heapq import _heapify_max, _heappop_max

-    heapq._siftdown_max(heap, 0, len(heap) - 1)

-    heappush(heap, item): itemをheapにpush

-    heappop(heap): heapから最小値を取得 空の場合はIndexError

-    max heapにする場合は、prefix: _ とsuffix: _maxをつければ良い

-    h = [0] + list(map(int, input().split()))

+    h = list(map(int, input().split()))

-        if (not ai) or hi > _heappop_max(ai):


Input:
n = int(eval(input()))

total = 0

h = list(map(int, input().split(" ")))

for i in range(1, n):

    if h[i] < h[i - 1]:

        total += abs(h[i] - h[i-1])

        h[i] = h[i - 1]

print(total)

n = int(eval(input()))

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

answer = 0

for i in range(1,n):

    if a[i] < a[i - 1]:

        answer += a[i-1] - a[i]

        a[i]= a[i - 1]

print(answer)

n = int(eval(input()))
total = 0
h = list(map(int, input().split(" ")))
for i in range(1, n):
    if h[i] < h[i - 1]:
        total += abs(h[i] - h[i - 1])
        h[i] = h[i - 1]
print(total)

n = int(eval(input()))
a = list(map(int, input().split(" ")))
answer = 0
for i in range(1, n):
    if a[i] < a[i - 1]:
        answer += a[i - 1] - a[i]
        a[i] = a[i - 1]
print(answer)

-total = 0
-h = list(map(int, input().split(" ")))
+a = list(map(int, input().split(" ")))
+answer = 0
-    if h[i] < h[i - 1]:
-        total += abs(h[i] - h[i - 1])
-        h[i] = h[i - 1]
-print(total)
+    if a[i] < a[i - 1]:
+        answer += a[i - 1] - a[i]
+        a[i] = a[i - 1]
+print(answer)


Input:
N, M = list(map(int, input().split()))

s = [int(c) for c in input().split()]

t = [int(c) for c in input().split()]

MOD = 10**9+7

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

dp_cum = [[0]*(M+1) for i in range(N+1)]

dp[0][0] = 1

for i in range(N+1):

  dp_cum[i][0] = 1

for j in range(M+1):

  dp_cum[0][j] = 1

for i in range(N):

  for j in range(M):

    if s[i]!=t[j]:

      dp[i+1][j+1] = 0

    else:

      dp[i+1][j+1] = dp_cum[i][j]

    dp_cum[i+1][j+1] = dp_cum[i][j+1] + dp_cum[i+1][j] - dp_cum[i][j] + dp[i+1][j+1]

    dp_cum[i+1][j+1] %= MOD

print((dp_cum[-1][-1]))

import numpy as np

MOD = 10**9+7

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

s = np.array(input().split(), dtype=np.int32)

t = np.array(input().split(), dtype=np.int32)

dp = np.zeros((N+1,M+1), dtype=np.int64)

dp[0] = 1

for i in range(N):

  same = (s[i]==t)

  dp[i+1,1:][same] = dp[i,:-1][same]

  dp[i+1] = (dp[i+1].cumsum()+dp[i])%MOD

print((dp[-1,-1]))

N, M = list(map(int, input().split()))
s = [int(c) for c in input().split()]
t = [int(c) for c in input().split()]
MOD = 10**9 + 7
dp = [[0] * (M + 1) for i in range(N + 1)]
dp_cum = [[0] * (M + 1) for i in range(N + 1)]
dp[0][0] = 1
for i in range(N + 1):
    dp_cum[i][0] = 1
for j in range(M + 1):
    dp_cum[0][j] = 1
for i in range(N):
    for j in range(M):
        if s[i] != t[j]:
            dp[i + 1][j + 1] = 0
        else:
            dp[i + 1][j + 1] = dp_cum[i][j]
        dp_cum[i + 1][j + 1] = (
            dp_cum[i][j + 1] + dp_cum[i + 1][j] - dp_cum[i][j] + dp[i + 1][j + 1]
        )
        dp_cum[i + 1][j + 1] %= MOD
print((dp_cum[-1][-1]))

import numpy as np

MOD = 10**9 + 7
N, M = list(map(int, input().split()))
s = np.array(input().split(), dtype=np.int32)
t = np.array(input().split(), dtype=np.int32)
dp = np.zeros((N + 1, M + 1), dtype=np.int64)
dp[0] = 1
for i in range(N):
    same = s[i] == t
    dp[i + 1, 1:][same] = dp[i, :-1][same]
    dp[i + 1] = (dp[i + 1].cumsum() + dp[i]) % MOD
print((dp[-1, -1]))

-dp_cum = [[0] * (M + 1) for i in range(N + 1)]

+s = np.array(input().split(), dtype=np.int32)

+t = np.array(input().split(), dtype=np.int32)

+dp = np.zeros((N + 1, M + 1), dtype=np.int64)


Input:
def main():

    n, *a, = list(map(int, open(0).read().split()))

    m = max(a)

    d = [0] * (m + 1)

    d[1] = 1

    for i in range(2, m + 1):

        for j in range(i, m + 1, i):

            if d[j] == 0:

                d[j] = i

    def primes(x):

        ps = set()

        while x != 1:

            p = d[x]

            ps.add(p)

            x = x // d[x]

        return ps

    b = set()

    c = primes(a[0])

    f = 0

    for i in a:

        ps = primes(i)

        if f == 0:

            if b & ps:

                f = 1

            b |= ps

        c &= ps

    else:

        if f == 1 and len(c) > 0:

            f = 2

    ans = ["pairwise coprime", "setwise coprime", "not coprime"][f]

    print(ans)

if __name__ == '__main__':

    main()

from functools import reduce
def main():

    from math import gcd

    from functools import reduce

    n, *a, = list(map(int, open(0).read().split()))

    m = max(a)

    d = [0] * (m + 1)

    d[1] = 1

    for i in range(2, m + 1):

        for j in range(i, m + 1, i):

            if d[j] == 0:

                d[j] = i

    def primes(x):

        ps = set()

        while x != 1:

            p = d[x]

            ps.add(p)

            x = x // d[x]

        return ps

    b = set()

    f = 0

    for i in a:

        ps = primes(i)

        if b & ps:

            f = 1

            break

        b |= ps

    if f > 0 and reduce(gcd, a) != 1:

        f = 2

    ans = ["pairwise coprime", "setwise coprime", "not coprime"][f]

    print(ans)

if __name__ == '__main__':

    main()

def main():
    (
        n,
        *a,
    ) = list(map(int, open(0).read().split()))
    m = max(a)
    d = [0] * (m + 1)
    d[1] = 1
    for i in range(2, m + 1):
        for j in range(i, m + 1, i):
            if d[j] == 0:
                d[j] = i

    def primes(x):
        ps = set()
        while x != 1:
            p = d[x]
            ps.add(p)
            x = x // d[x]
        return ps

    b = set()
    c = primes(a[0])
    f = 0
    for i in a:
        ps = primes(i)
        if f == 0:
            if b & ps:
                f = 1
            b |= ps
        c &= ps
    else:
        if f == 1 and len(c) > 0:
            f = 2
    ans = ["pairwise coprime", "setwise coprime", "not coprime"][f]
    print(ans)

if __name__ == "__main__":
    main()

from functools import reduce

def main():
    from math import gcd
    from functools import reduce

    (
        n,
        *a,
    ) = list(map(int, open(0).read().split()))
    m = max(a)
    d = [0] * (m + 1)
    d[1] = 1
    for i in range(2, m + 1):
        for j in range(i, m + 1, i):
            if d[j] == 0:
                d[j] = i

    def primes(x):
        ps = set()
        while x != 1:
            p = d[x]
            ps.add(p)
            x = x // d[x]
        return ps

    b = set()
    f = 0
    for i in a:
        ps = primes(i)
        if b & ps:
            f = 1
            break
        b |= ps
    if f > 0 and reduce(gcd, a) != 1:
        f = 2
    ans = ["pairwise coprime", "setwise coprime", "not coprime"][f]
    print(ans)

if __name__ == "__main__":
    main()

+from functools import reduce
+
+
+    from math import gcd
+    from functools import reduce
+
-    c = primes(a[0])
-        if f == 0:
-            if b & ps:
-                f = 1
-            b |= ps
-        c &= ps
-    else:
-        if f == 1 and len(c) > 0:
-            f = 2
+        if b & ps:
+            f = 1
+            break
+        b |= ps
+    if f > 0 and reduce(gcd, a) != 1:
+        f = 2


Input:
L, *A = list(map(int, open(0)))

D = [(2, 1), (1, 0), (0, 1)]

s0 = s1 = s2 = s3 = s4 = 0

for a in A:

    e, o = D[(a - 1) % 2 + 1 if a else 0]

    s0 += a

    s1 = s0 if s0 < s1 + e else s1 + e

    s2 = s1 if s1 < s2 + o else s2 + o

    s3 = s2 if s2 < s3 + e else s3 + e

    s4 = s3 if s3 < s4 + a else s4 + a

print((min(s0, s1, s2, s3, s4)))

def main():

    L, *A = list(map(int, open(0)))

    D = [(2, 1), (1, 0), (0, 1)]

    s0 = s1 = s2 = s3 = s4 = 0

    for a in A:

        e, o = D[(a - 1) % 2 + 1 if a else 0]

        s0 += a

        s1 = s0 if s0 < s1 + e else s1 + e

        s2 = s1 if s1 < s2 + o else s2 + o

        s3 = s2 if s2 < s3 + e else s3 + e

        s4 = s3 if s3 < s4 + a else s4 + a

    print((min(s0, s1, s2, s3, s4)))

if __name__ == '__main__':

    main()

def main():
    L, *A = list(map(int, open(0)))
    D = [(2, 1), (1, 0), (0, 1)]
    s0 = s1 = s2 = s3 = s4 = 0
    for a in A:
        e, o = D[(a - 1) % 2 + 1 if a else 0]
        s0 += a
        s1 = s0 if s0 < s1 + e else s1 + e
        s2 = s1 if s1 < s2 + o else s2 + o
        s3 = s2 if s2 < s3 + e else s3 + e
        s4 = s3 if s3 < s4 + a else s4 + a
    print((min(s0, s1, s2, s3, s4)))

if __name__ == "__main__":
    main()

+        s1 = s0 if s0 < s1 + e else s1 + e

+        s2 = s1 if s1 < s2 + o else s2 + o

+        s3 = s2 if s2 < s3 + e else s3 + e

+        s4 = s3 if s3 < s4 + a else s4 + a


Input:
# -*-*-*- coding: utf-8 -*-*-*-

member = int(eval(input()))

days, choco = list(map(int, input().split()))

ans = choco

for i in range(member):

    num = int(eval(input()))

    if days % num == 0:

        ans -= 1

    ans += days // num + 1

#    print(i, 'day : eat = {} // {} = {:2}, ans = {:2}'.format(days, num, (days // num + 1), ans))

print(ans)

# -*-*-*- coding: utf-8 -*-*-*-

member = int(eval(input()))

days, choco = list(map(int, input().split()))

ans = choco

for i in range(member):

    num = int(eval(input()))

    ans += (days - 1) // num + 1

#    print(i, 'day : eat = {} // {} = {:2}, ans = {:2}'.format(days, num, (days // num + 1), ans))

print(ans)

-    if days % num == 0:
-        ans -= 1
-    ans += days // num + 1
+    ans += (days - 1) // num + 1


Input:
from heapq import heappop, heappush

def solve(field, s, t, k):

    INF = 10 ** 18

    ans = [[INF, INF] for _ in field]

    ans[s][0] = ans[s][1] = 0

    MOVE = [(-w2, 0), (-1, 1), (1, 1), (w2, 0)]

    q = [(0, s, 0)]

    while q:

        cost, v, direction = heappop(q)

        if v == t:

            return (cost - 1) // k + 1

        ceiling = ((cost - 1) // k + 1) * k + 1

        for di, ax in MOVE:

            u = v + di

            if field[u] == '@':

                continue

            nc = cost + 1 if di == direction else ceiling

            if ans[u][ax] <= nc:

                continue

            ans[u][ax] = nc

            heappush(q, (nc, u, di))

    return -1

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

x1, y1, x2, y2 = list(map(int, input().split()))

h2 = h + 2

w2 = w + 2

field_tmp = [eval(input()) for _ in range(h)]

field = ['@' * w2]

for row in field_tmp:

    field.append('@')

    field.append(row)

    field.append('@')

field.append('@' * w2)

field = ''.join(field)

s = x1 * w2 + y1

t = x2 * w2 + y2

print((solve(field, s, t, k)))

from heapq import heappop, heappush

def solve(field, s, t, k):

    INF = 10 ** 18

    ans = [[INF, INF] for _ in field]

    ans[s][0] = ans[s][1] = 0

    MOVE = [(-w2, 0), (-1, 1), (1, 1), (w2, 0)]

    q = [(0, s, 0)]

    while q:

        cost, v, direction = heappop(q)

        if v == t:

            return (cost - 1) // k + 1

        ceiling = -1

        for di, ax in MOVE:

            u = v + di

            if field[u] == '@':

                continue

            nc = cost + 1 if di == direction else ceiling

            if nc == -1:

                nc = ceiling = ((cost - 1) // k + 1) * k + 1

            if ans[u][ax] <= nc:

                continue

            ans[u][ax] = nc

            heappush(q, (nc, u, di))

    return -1

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

x1, y1, x2, y2 = list(map(int, input().split()))

h2 = h + 2

w2 = w + 2

field_tmp = [eval(input()) for _ in range(h)]

field = ['@' * w2]

for row in field_tmp:

    field.append('@')

    field.append(row)

    field.append('@')

field.append('@' * w2)

field = ''.join(field)

s = x1 * w2 + y1

t = x2 * w2 + y2

print((solve(field, s, t, k)))

from heapq import heappop, heappush

def solve(field, s, t, k):
    INF = 10**18
    ans = [[INF, INF] for _ in field]
    ans[s][0] = ans[s][1] = 0
    MOVE = [(-w2, 0), (-1, 1), (1, 1), (w2, 0)]
    q = [(0, s, 0)]
    while q:
        cost, v, direction = heappop(q)
        if v == t:
            return (cost - 1) // k + 1
        ceiling = ((cost - 1) // k + 1) * k + 1
        for di, ax in MOVE:
            u = v + di
            if field[u] == "@":
                continue
            nc = cost + 1 if di == direction else ceiling
            if ans[u][ax] <= nc:
                continue
            ans[u][ax] = nc
            heappush(q, (nc, u, di))
    return -1

h, w, k = list(map(int, input().split()))
x1, y1, x2, y2 = list(map(int, input().split()))
h2 = h + 2
w2 = w + 2
field_tmp = [eval(input()) for _ in range(h)]
field = ["@" * w2]
for row in field_tmp:
    field.append("@")
    field.append(row)
    field.append("@")
field.append("@" * w2)
field = "".join(field)
s = x1 * w2 + y1
t = x2 * w2 + y2
print((solve(field, s, t, k)))

from heapq import heappop, heappush

def solve(field, s, t, k):
    INF = 10**18
    ans = [[INF, INF] for _ in field]
    ans[s][0] = ans[s][1] = 0
    MOVE = [(-w2, 0), (-1, 1), (1, 1), (w2, 0)]
    q = [(0, s, 0)]
    while q:
        cost, v, direction = heappop(q)
        if v == t:
            return (cost - 1) // k + 1
        ceiling = -1
        for di, ax in MOVE:
            u = v + di
            if field[u] == "@":
                continue
            nc = cost + 1 if di == direction else ceiling
            if nc == -1:
                nc = ceiling = ((cost - 1) // k + 1) * k + 1
            if ans[u][ax] <= nc:
                continue
            ans[u][ax] = nc
            heappush(q, (nc, u, di))
    return -1

h, w, k = list(map(int, input().split()))
x1, y1, x2, y2 = list(map(int, input().split()))
h2 = h + 2
w2 = w + 2
field_tmp = [eval(input()) for _ in range(h)]
field = ["@" * w2]
for row in field_tmp:
    field.append("@")
    field.append(row)
    field.append("@")
field.append("@" * w2)
field = "".join(field)
s = x1 * w2 + y1
t = x2 * w2 + y2
print((solve(field, s, t, k)))


Input:
from sys import stdin, setrecursionlimit

from itertools import accumulate

setrecursionlimit(10 ** 9)

INF = 1 << 60

def input():

    return stdin.readline().strip()

def prime_numbers(n):

    if n < 2:

        return []

    m = (n + 1) // 2

    p = [True] * m

    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):

        if p[i]:

            for j in range(2 * i * (i + 1), m, 2 * i + 1):

                p[j] = False

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}

N = 10 ** 5

primes = prime_numbers(N)

a = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(N + 1)]

a = list(accumulate(a))

ans = []

Q, *LR = map(int, open(0).read().split())

for l, r in zip(*[iter(LR)] * 2):

    ans.append(a[r] - a[l - 1])

print(*ans, sep='\n')

from sys import stdin, setrecursionlimit

from itertools import accumulate

setrecursionlimit(10 ** 9)

INF = 1 << 60

def input():

    return stdin.readline().strip()

def prime_numbers(n):

    if n < 2:

        return []

    m = (n + 1) // 2

    p = [True] * m

    for i in range(1, int((n ** 0.5 - 1) / 2) + 1):

        if p[i]:

            for j in range(2 * i * (i + 1), m, 2 * i + 1):

                p[j] = False

    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}

N = 10 ** 5

primes = prime_numbers(N)

a = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(N + 1)]

a = list(accumulate(a))

ans = []

Q, *LR = list(map(int, open(0).read().split()))

for l, r in zip(*[iter(LR)] * 2):

    ans.append(a[r] - a[l - 1])

print(('\n'.join(map(str, ans))))

from sys import stdin, setrecursionlimit
from itertools import accumulate

setrecursionlimit(10**9)
INF = 1 << 60

def input():
    return stdin.readline().strip()

def prime_numbers(n):
    if n < 2:
        return []
    m = (n + 1) // 2
    p = [True] * m
    for i in range(1, int((n**0.5 - 1) / 2) + 1):
        if p[i]:
            for j in range(2 * i * (i + 1), m, 2 * i + 1):
                p[j] = False
    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}

N = 10**5
primes = prime_numbers(N)
a = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(N + 1)]
a = list(accumulate(a))
ans = []
Q, *LR = map(int, open(0).read().split())
for l, r in zip(*[iter(LR)] * 2):
    ans.append(a[r] - a[l - 1])
print(*ans, sep="\n")

from sys import stdin, setrecursionlimit
from itertools import accumulate

setrecursionlimit(10**9)
INF = 1 << 60

def input():
    return stdin.readline().strip()

def prime_numbers(n):
    if n < 2:
        return []
    m = (n + 1) // 2
    p = [True] * m
    for i in range(1, int((n**0.5 - 1) / 2) + 1):
        if p[i]:
            for j in range(2 * i * (i + 1), m, 2 * i + 1):
                p[j] = False
    return {2} | {2 * i + 1 for i in range(1, m) if p[i]}

N = 10**5
primes = prime_numbers(N)
a = [1 if n in primes and (n + 1) // 2 in primes else 0 for n in range(N + 1)]
a = list(accumulate(a))
ans = []
Q, *LR = list(map(int, open(0).read().split()))
for l, r in zip(*[iter(LR)] * 2):
    ans.append(a[r] - a[l - 1])
print(("\n".join(map(str, ans))))

-Q, *LR = map(int, open(0).read().split())

+Q, *LR = list(map(int, open(0).read().split()))


Input:
def main():

    n, k, *x = list(map(int, open(0).read().split()))

    f = lambda i: x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))

    l = f(0)

    for i in range(n - k + 1):

        y = f(i)

        if y < l:

            l = y

    print(l)

if __name__ == '__main__':

    main()

def main():

    n, k, *x = list(map(int, open(0).read().split()))

    l = x[0 + k - 1] - x[0] + min(abs(x[0 + k - 1]), abs(x[0]))

    for i in range(n - k + 1):

        y = x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))

        if y < l:

            l = y

    print(l)

if __name__ == '__main__':

    main()

def main():
    n, k, *x = list(map(int, open(0).read().split()))
    f = lambda i: x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
    l = f(0)
    for i in range(n - k + 1):
        y = f(i)
        if y < l:
            l = y
    print(l)

if __name__ == "__main__":
    main()

def main():
    n, k, *x = list(map(int, open(0).read().split()))
    l = x[0 + k - 1] - x[0] + min(abs(x[0 + k - 1]), abs(x[0]))
    for i in range(n - k + 1):
        y = x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))
        if y < l:
            l = y
    print(l)

if __name__ == "__main__":
    main()

-    f = lambda i: x[i + k - 1] - x[i] + min(abs(x[i + k - 1]), abs(x[i]))


Input:
import bisect

N = int(eval(input()))

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

L.sort()

ans = 0

for i in range(N-2):

    for j in range(N-i-1):

        a = L[i]

        b = L[i+j+1]

        c_right = bisect.bisect_left(L[i+j+2:], b + a)

        ans += c_right

print(ans)

import bisect

N = int(eval(input()))

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

L.sort()

ans = 0

for i in range(N-2):

    for j in range(N-i-1):

        a = L[i]

        b = L[i+j+1]

        c_right = bisect.bisect_left(L, b + a, i+j+2)

        ans += c_right - (i+j+2)

print(ans)

import bisect

N = int(eval(input()))
L = list(map(int, input().split()))
L.sort()
ans = 0
for i in range(N - 2):
    for j in range(N - i - 1):
        a = L[i]
        b = L[i + j + 1]
        c_right = bisect.bisect_left(L[i + j + 2 :], b + a)
        ans += c_right
print(ans)

import bisect

N = int(eval(input()))
L = list(map(int, input().split()))
L.sort()
ans = 0
for i in range(N - 2):
    for j in range(N - i - 1):
        a = L[i]
        b = L[i + j + 1]
        c_right = bisect.bisect_left(L, b + a, i + j + 2)
        ans += c_right - (i + j + 2)
print(ans)

-        c_right = bisect.bisect_left(L[i + j + 2 :], b + a)

+        c_right = bisect.bisect_left(L, b + a, i + j + 2)


Input:
Tmp = []

Tmp  = input().rstrip().split(' ')

A = int(Tmp[0])

B = int(Tmp[1])

Ans = 0

Data = A

while Data <= B:

    C = Data // 10000

    D = (Data - C * 10000 )// 1000

    E = Data // 100

    F = (Data - E * 100 )// 10

    G = Data % 10

    if (C==G) and (D==F):

        Ans += 1

    Data += 1

print(Ans)

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

N = B - A + 1

Ans = 0

for i in range(N):

  TmpN = A + i

  S = str(TmpN)

  if S[0]==S[4] and S[1]==S[3]:

    Ans += 1

print(Ans)

Tmp = []
Tmp = input().rstrip().split(" ")
A = int(Tmp[0])
B = int(Tmp[1])
Ans = 0
Data = A
while Data <= B:
    C = Data // 10000
    D = (Data - C * 10000) // 1000
    E = Data // 100
    F = (Data - E * 100) // 10
    G = Data % 10
    if (C == G) and (D == F):
        Ans += 1
    Data += 1
print(Ans)

A, B = list(map(int, input().split()))
N = B - A + 1
Ans = 0
for i in range(N):
    TmpN = A + i
    S = str(TmpN)
    if S[0] == S[4] and S[1] == S[3]:
        Ans += 1
print(Ans)

-Tmp = []
-Tmp = input().rstrip().split(" ")
-A = int(Tmp[0])
-B = int(Tmp[1])
+A, B = list(map(int, input().split()))
+N = B - A + 1
-Data = A
-while Data <= B:
-    C = Data // 10000
-    D = (Data - C * 10000) // 1000
-    E = Data // 100
-    F = (Data - E * 100) // 10
-    G = Data % 10
-    if (C == G) and (D == F):
+for i in range(N):
+    TmpN = A + i
+    S = str(TmpN)
+    if S[0] == S[4] and S[1] == S[3]:
-    Data += 1


Input:
c = {}

n = int(eval(input()))

r = 0

for _ in range(n):

    s = ''.join(sorted(eval(input())))

    v = c.get(s, 0)

    r += v

    c[s] = v + 1

print(r)

from collections import Counter

c = Counter(''.join(sorted(eval(input()))) for _ in range(int(eval(input()))))

print((sum(x * (x - 1) // 2 for x in list(c.values()))))

c = {}
n = int(eval(input()))
r = 0
for _ in range(n):
    s = "".join(sorted(eval(input())))
    v = c.get(s, 0)
    r += v
    c[s] = v + 1
print(r)

from collections import Counter

c = Counter("".join(sorted(eval(input()))) for _ in range(int(eval(input()))))
print((sum(x * (x - 1) // 2 for x in list(c.values()))))

+c = Counter("".join(sorted(eval(input()))) for _ in range(int(eval(input()))))

+print((sum(x * (x - 1) // 2 for x in list(c.values()))))


Input:
from collections import defaultdict

MOD = 10 ** 9 + 7

def main():

    N = int(eval(input()))

    ans = 1

    for i in range(1, N + 1):

        ans *= i

        ans %= MOD

    print((ans % MOD))

if __name__ == '__main__':

    main()

from collections import defaultdict

MOD = 10 ** 9 + 7

def main():

    N = int(eval(input()))

    ans = 1

    for i in range(1, N + 1):

        ans = (ans * i) % MOD

    print(ans)

if __name__ == '__main__':

    main()

from collections import defaultdict

MOD = 10**9 + 7

def main():
    N = int(eval(input()))
    ans = 1
    for i in range(1, N + 1):
        ans *= i
        ans %= MOD
    print((ans % MOD))

if __name__ == "__main__":
    main()

from collections import defaultdict

MOD = 10**9 + 7

def main():
    N = int(eval(input()))
    ans = 1
    for i in range(1, N + 1):
        ans = (ans * i) % MOD
    print(ans)

if __name__ == "__main__":
    main()

-        ans *= i
-        ans %= MOD
-    print((ans % MOD))
+        ans = (ans * i) % MOD
+    print(ans)


Input:
import math

from decimal import Decimal

n = int(eval(input()))

i = 0

list = []

while i < n:

   list.append(input().split())

   i += 1

h = 0

th = 1

ah = 1

while h < n:

     listh = list[h]

     x = int(listh[0])

     y = int(listh[1])

     m = max(math.ceil(th/x),math.ceil(ah/y))

     th = Decimal(m*x)

     ah = Decimal(m*y)

     h += 1

print((th+ah))

import math

from decimal import Decimal

n = int(eval(input()))

i = 0

list = []

while i < n:

   list.append(input().split())

   i += 1

h = 0

th = 1

ah = 1

while h < n:

     listh = list[h]

     x = int(listh[0])

     y = int(listh[1])

     m = max((th+x-1)//x, (ah+y-1)//y)

     th = m*x

     ah = m*y

     h += 1

print((th+ah))

import math
from decimal import Decimal

n = int(eval(input()))
i = 0
list = []
while i < n:
    list.append(input().split())
    i += 1
h = 0
th = 1
ah = 1
while h < n:
    listh = list[h]
    x = int(listh[0])
    y = int(listh[1])
    m = max(math.ceil(th / x), math.ceil(ah / y))
    th = Decimal(m * x)
    ah = Decimal(m * y)
    h += 1
print((th + ah))

import math
from decimal import Decimal

n = int(eval(input()))
i = 0
list = []
while i < n:
    list.append(input().split())
    i += 1
h = 0
th = 1
ah = 1
while h < n:
    listh = list[h]
    x = int(listh[0])
    y = int(listh[1])
    m = max((th + x - 1) // x, (ah + y - 1) // y)
    th = m * x
    ah = m * y
    h += 1
print((th + ah))

-    m = max(math.ceil(th / x), math.ceil(ah / y))


Input:
# C

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

graph = [[False]*N for _ in range(N)]

visited = [False]*N

def dfs(cur):

    global visited

    visited[cur] = True

    for nxt in range(N):

        if graph[cur][nxt]==False: continue

        if visited[nxt]==True: continue

        dfs(nxt)

a = [-1]*M

b = [-1]*M

for i in range(M):

    ai,bi = list(map(int, input().split()))

    a[i],b[i] = ai-1, bi-1

    graph[a[i]][b[i]] = True

    graph[b[i]][a[i]] = True

ans = 0

for i in range(M):

    graph[a[i]][b[i]] = False # 辺を消す

    graph[b[i]][a[i]] = False

    # print("graph: "+"\n".join(map(str, graph)))

    visited = [False]*N

    dfs(0)

    if not all(visited):

        ans += 1

    graph[a[i]][b[i]] = True # 辺を戻す

    graph[b[i]][a[i]] = True

print(ans)

class UnionFind:

    """

    - sizeを指定

    - 要素をグループにまとめる(unite)

    - 要素同士が同じグループか判定する(isSame)

    - 分離はできない

    - par: 親の番号(はじめ par[i]==i つまりすべての頂点が根)

     - 始め各要素は別々のグループ"""

    def __init__(self, size: int):

        self.par = [-1]*size

        for i in range(size):

            self.par[i] = i

    def root(self, x: int) -> int:

        """根を求める"""

        if self.par[x] == x: # if root

            return x

        else:

            self.par[x] = self.root(self.par[x]) # 経路圧縮

            return self.par[x]

    def isSame(self, x:int, y:int)->bool:

        """x と y が同じ集合に属するか否か"""

        return self.root(x)==self.root(y)

    def unite(self, x:int, y:int):

        """x と y の属する集合を併合"""

        x = self.root(x)

        y = self.root(y)

        if x == y: return

        self.par[x] = y

##### main #####

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

a,b = [0]*M, [0]*M

for i in range(M):

    ai,bi = list(map(int, input().split()))

    a[i],b[i] = ai-1, bi-1

ans = 0

for i in range(M):

    uf = UnionFind(N)

    for j in range(M):

        if i==j: continue # この辺はパス

        uf.unite(a[j], b[j])

    bridge = False

    for i in range(N):

        if not uf.isSame(0,i):

            bridge = True

    if bridge:

        ans += 1

print(ans)

# C
N, M = list(map(int, input().split()))
graph = [[False] * N for _ in range(N)]
visited = [False] * N

def dfs(cur):
    global visited
    visited[cur] = True
    for nxt in range(N):
        if graph[cur][nxt] == False:
            continue
        if visited[nxt] == True:
            continue
        dfs(nxt)

a = [-1] * M
b = [-1] * M
for i in range(M):
    ai, bi = list(map(int, input().split()))
    a[i], b[i] = ai - 1, bi - 1
    graph[a[i]][b[i]] = True
    graph[b[i]][a[i]] = True
ans = 0
for i in range(M):
    graph[a[i]][b[i]] = False  # 辺を消す
    graph[b[i]][a[i]] = False
    # print("graph: "+"\n".join(map(str, graph)))
    visited = [False] * N
    dfs(0)
    if not all(visited):
        ans += 1
    graph[a[i]][b[i]] = True  # 辺を戻す
    graph[b[i]][a[i]] = True
print(ans)

class UnionFind:
    """
    - sizeを指定
    - 要素をグループにまとめる(unite)
    - 要素同士が同じグループか判定する(isSame)
    - 分離はできない
    - par: 親の番号(はじめ par[i]==i つまりすべての頂点が根)
     - 始め各要素は別々のグループ"""

    def __init__(self, size: int):
        self.par = [-1] * size
        for i in range(size):
            self.par[i] = i

    def root(self, x: int) -> int:
        """根を求める"""
        if self.par[x] == x:  # if root
            return x
        else:
            self.par[x] = self.root(self.par[x])  # 経路圧縮
            return self.par[x]

    def isSame(self, x: int, y: int) -> bool:
        """x と y が同じ集合に属するか否か"""
        return self.root(x) == self.root(y)

    def unite(self, x: int, y: int):
        """x と y の属する集合を併合"""
        x = self.root(x)
        y = self.root(y)
        if x == y:
            return
        self.par[x] = y

##### main #####
N, M = list(map(int, input().split()))
a, b = [0] * M, [0] * M
for i in range(M):
    ai, bi = list(map(int, input().split()))
    a[i], b[i] = ai - 1, bi - 1
ans = 0
for i in range(M):
    uf = UnionFind(N)
    for j in range(M):
        if i == j:
            continue  # この辺はパス
        uf.unite(a[j], b[j])
    bridge = False
    for i in range(N):
        if not uf.isSame(0, i):
            bridge = True
    if bridge:
        ans += 1
print(ans)

-graph = [[False] * N for _ in range(N)]

+    - 要素をグループにまとめる(unite)

+    - 要素同士が同じグループか判定する(isSame)

+    - 分離はできない

+    - par: 親の番号(はじめ par[i]==i つまりすべての頂点が根)

+     - 始め各要素は別々のグループ"""

+        if self.par[x] == x:  # if root

+            self.par[x] = self.root(self.par[x])  # 経路圧縮

+    def isSame(self, x: int, y: int) -> bool:

+        """x と y が同じ集合に属するか否か"""

+        return self.root(x) == self.root(y)

+        """x と y の属する集合を併合"""

-    # print("graph: "+"\n".join(map(str, graph)))


Input:
N = int(eval(input()))

ABC = []

for _ in range(N):

        a,b,c = list(map(int,input().split()))

        ABC.append((a,b,c))

dpA = [ABC[0][0]]*N

dpB = [ABC[0][1]]*N

dpC = [ABC[0][2]]*N

for i in range(1, N):

        dpA[i] = max(dpB[i-1] + ABC[i][0], dpC[i-1] + ABC[i][0])

        dpB[i] = max(dpA[i-1] + ABC[i][1], dpC[i-1] + ABC[i][1])

        dpC[i] = max(dpA[i-1] + ABC[i][2], dpB[i-1] + ABC[i][2])

print((max(dpA[N-1], dpB[N-1], dpC[N-1])))

N = int(eval(input()))

for i in range(N):

        a,b,c = list(map(int,input().split()))

        if i == 0:

                preA = a

                preB = b

                preC = c

        else:

                A = max(preB + a, preC + a)

                B = max(preA + b, preC + b)

                C = max(preA + c, preB + c)

                preA = A

                preB = B

                preC = C

print((max(preA, preB, preC)))

N = int(eval(input()))
ABC = []
for _ in range(N):
    a, b, c = list(map(int, input().split()))
    ABC.append((a, b, c))
dpA = [ABC[0][0]] * N
dpB = [ABC[0][1]] * N
dpC = [ABC[0][2]] * N
for i in range(1, N):
    dpA[i] = max(dpB[i - 1] + ABC[i][0], dpC[i - 1] + ABC[i][0])
    dpB[i] = max(dpA[i - 1] + ABC[i][1], dpC[i - 1] + ABC[i][1])
    dpC[i] = max(dpA[i - 1] + ABC[i][2], dpB[i - 1] + ABC[i][2])
print((max(dpA[N - 1], dpB[N - 1], dpC[N - 1])))

N = int(eval(input()))
for i in range(N):
    a, b, c = list(map(int, input().split()))
    if i == 0:
        preA = a
        preB = b
        preC = c
    else:
        A = max(preB + a, preC + a)
        B = max(preA + b, preC + b)
        C = max(preA + c, preB + c)
        preA = A
        preB = B
        preC = C
print((max(preA, preB, preC)))


Input:
def resolve():

    INF = 10 ** 18

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

    Cost = [0] * M

    Box_key = [0] * M

    for i in range(M):

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

        Cost[i] = a

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

        Box_key[i] = sum(1 << (c - 1) for c in C)

    # dp[ i ][ S ] := 最初の i 個の鍵からいくつか選んで、

    # 開いた宝箱の集合が S で表されるような場合についての、最小コスト

    dp = [[INF] * (1 << N) for _ in range(M + 1)]

    dp[0][0] = 0

    for i in range(M):

        for j in range(1 << N):

            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])

            dp[i + 1][j | Box_key[i]] = min(dp[i + 1][j | Box_key[i]], dp[i][j] + Cost[i])

    if dp[M][(1 << N) - 1] == INF:

        print((-1))

    else:

        print((dp[M][(1 << N) - 1]))

if __name__ == "__main__":

    resolve()

def resolve():

    INF = 10 ** 18

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

    Box_key = []

    for i in range(M):

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

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

        s = sum(1 << (c - 1) for c in C)

        Box_key.append((s, a))

    # dp[i]: 集合iの宝箱を開ける最小コスト

    dp = [INF] * (1 << N)

    dp[0] = 0

    for s in range(1 << N):

        for i in range(M):

            ns = s | Box_key[i][0]

            cost = dp[s] + Box_key[i][1]

            dp[ns] = min(dp[ns], cost)

    if dp[(1 << N) - 1] == INF:

        print((-1))

    else:

        print((dp[(1 << N) - 1]))

if __name__ == "__main__":

    resolve()

def resolve():
    INF = 10**18
    N, M = list(map(int, input().split()))
    Cost = [0] * M
    Box_key = [0] * M
    for i in range(M):
        a, b = list(map(int, input().split()))
        Cost[i] = a
        C = list(map(int, input().split()))
        Box_key[i] = sum(1 << (c - 1) for c in C)
    # dp[ i ][ S ] := 最初の i 個の鍵からいくつか選んで、
    # 開いた宝箱の集合が S で表されるような場合についての、最小コスト
    dp = [[INF] * (1 << N) for _ in range(M + 1)]
    dp[0][0] = 0
    for i in range(M):
        for j in range(1 << N):
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])
            dp[i + 1][j | Box_key[i]] = min(
                dp[i + 1][j | Box_key[i]], dp[i][j] + Cost[i]
            )
    if dp[M][(1 << N) - 1] == INF:
        print((-1))
    else:
        print((dp[M][(1 << N) - 1]))

if __name__ == "__main__":
    resolve()

def resolve():
    INF = 10**18
    N, M = list(map(int, input().split()))
    Box_key = []
    for i in range(M):
        a, b = list(map(int, input().split()))
        C = list(map(int, input().split()))
        s = sum(1 << (c - 1) for c in C)
        Box_key.append((s, a))
    # dp[i]: 集合iの宝箱を開ける最小コスト
    dp = [INF] * (1 << N)
    dp[0] = 0
    for s in range(1 << N):
        for i in range(M):
            ns = s | Box_key[i][0]
            cost = dp[s] + Box_key[i][1]
            dp[ns] = min(dp[ns], cost)
    if dp[(1 << N) - 1] == INF:
        print((-1))
    else:
        print((dp[(1 << N) - 1]))

if __name__ == "__main__":
    resolve()

-        Box_key[i] = sum(1 << (c - 1) for c in C)

-    # dp[ i ][ S ] := 最初の i 個の鍵からいくつか選んで、

-    # 開いた宝箱の集合が S で表されるような場合についての、最小コスト

-    dp = [[INF] * (1 << N) for _ in range(M + 1)]

-            dp[i + 1][j | Box_key[i]] = min(

-                dp[i + 1][j | Box_key[i]], dp[i][j] + Cost[i]

+        s = sum(1 << (c - 1) for c in C)

+    # dp[i]: 集合iの宝箱を開ける最小コスト

+            cost = dp[s] + Box_key[i][1]


Input:
import math as M

def R(A): return (A[0]**2+A[1]**2)**.5

def I(i): return [list(map(int,input().split())) for _ in [0]*i]

def C(a,b): return a>b or abs(a-b)<1e-6

def f(e1):

  tx,ty,sx,sy=e1

  x=[]

  for e2 in WP:

    wx,wy,r=e2

    wt=[tx-wx,ty-wy]; rwt=R(wt)

    sw=[wx-sx,wy-sy]; rsw=R(sw)

    st=[tx-sx,ty-sy]; rst=R(st)

    F=[rwt<r,rsw<r]

    if rst==0: c=1

    elif F==[1,1]: c=1

    elif F==[1,0] or F==[0,1]: c=0

    elif F==[0,0]:

      a=M.pi/2-M.acos(r/rsw)

      b=M.acos(round((sw[0]*st[0]+sw[1]*st[1])/rsw/rst,4))

      if C(a,b) and C(rst**2,rsw**2-r**2): c=0

      else: c=1

    if c==0: return 0

    x.append(c)

  return all(x)

while 1:

  n=eval(input())

  if n==0: break

  WP=I(n)

  P=I(eval(input()))

  for e in P: print(["Safe","Danger"][f(e)])

import math as M

def R(A): return (A[0]**2+A[1]**2)**.5

def I(i): return [list(map(int,input().split())) for _ in [0]*i]

def C(a,b): return a>b or abs(a-b)<1e-6

def f(e1):

  tx,ty,sx,sy=e1

  x=[]

  st=[tx-sx,ty-sy]; rst=R(st)

  for e2 in WP:

    wx,wy,r=e2

    wt=[tx-wx,ty-wy]; rwt=R(wt)

    sw=[wx-sx,wy-sy]; rsw=R(sw)

    F=[rwt<r,rsw<r]

    c=1

    if F==[1,0] or F==[0,1]: return 0

    elif F==[0,0]:

      a=M.pi/2-M.acos(r/rsw)

      b=M.acos(round((sw[0]*st[0]+sw[1]*st[1])/rsw/rst,4))

      if C(a,b) and C(rst**2,rsw**2-r**2): return 0

    x.append(c)

  return all(x)

while 1:

  n=eval(input())

  if n==0: break

  WP=I(n)

  P=I(eval(input()))

  for e in P: print(["Safe","Danger"][f(e)])

import math as M

def R(A):
    return (A[0] ** 2 + A[1] ** 2) ** 0.5

def I(i):
    return [list(map(int, input().split())) for _ in [0] * i]

def C(a, b):
    return a > b or abs(a - b) < 1e-6

def f(e1):
    tx, ty, sx, sy = e1
    x = []
    for e2 in WP:
        wx, wy, r = e2
        wt = [tx - wx, ty - wy]
        rwt = R(wt)
        sw = [wx - sx, wy - sy]
        rsw = R(sw)
        st = [tx - sx, ty - sy]
        rst = R(st)
        F = [rwt < r, rsw < r]
        if rst == 0:
            c = 1
        elif F == [1, 1]:
            c = 1
        elif F == [1, 0] or F == [0, 1]:
            c = 0
        elif F == [0, 0]:
            a = M.pi / 2 - M.acos(r / rsw)
            b = M.acos(round((sw[0] * st[0] + sw[1] * st[1]) / rsw / rst, 4))
            if C(a, b) and C(rst**2, rsw**2 - r**2):
                c = 0
            else:
                c = 1
        if c == 0:
            return 0
        x.append(c)
    return all(x)

while 1:
    n = eval(input())
    if n == 0:
        break
    WP = I(n)
    P = I(eval(input()))
    for e in P:
        print(["Safe", "Danger"][f(e)])

import math as M

def R(A):
    return (A[0] ** 2 + A[1] ** 2) ** 0.5

def I(i):
    return [list(map(int, input().split())) for _ in [0] * i]

def C(a, b):
    return a > b or abs(a - b) < 1e-6

def f(e1):
    tx, ty, sx, sy = e1
    x = []
    st = [tx - sx, ty - sy]
    rst = R(st)
    for e2 in WP:
        wx, wy, r = e2
        wt = [tx - wx, ty - wy]
        rwt = R(wt)
        sw = [wx - sx, wy - sy]
        rsw = R(sw)
        F = [rwt < r, rsw < r]
        c = 1
        if F == [1, 0] or F == [0, 1]:
            return 0
        elif F == [0, 0]:
            a = M.pi / 2 - M.acos(r / rsw)
            b = M.acos(round((sw[0] * st[0] + sw[1] * st[1]) / rsw / rst, 4))
            if C(a, b) and C(rst**2, rsw**2 - r**2):
                return 0
        x.append(c)
    return all(x)

while 1:
    n = eval(input())
    if n == 0:
        break
    WP = I(n)
    P = I(eval(input()))
    for e in P:
        print(["Safe", "Danger"][f(e)])


Input:
n,x=list(map(int,input().split()))

l,p=[1],[1]

for i in range(n):

  l+=[l[-1]*2+3]

  p+=[p[-1]*2+1]

x-=1

a=0

while x>0 and n:

  t=l[n]//2

  if x>=t:

    a+=p[n-1]+1

    x-=t

  x-=1

  n-=1

if x>=0 and n==0: a+=1

print(a)


Input:
MOD = 10**9+7

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

patterns = [1,1,2,3,5,8,13,21]

dp = [ [0]*w for _ in range(h+1) ]

dp[0][0] = 1

for i in range(1,h+1):

    for wi in range(w):

        dp[i][wi] = dp[i-1][wi] * patterns[w-1-wi] * patterns[wi-0]

        if wi > 0:

            dp[i][wi] += dp[i-1][wi-1] * patterns[w-1-wi] * patterns[wi-1]

        if wi < w-1:

            dp[i][wi] += dp[i-1][wi+1] * patterns[w-1-wi-1] * patterns[wi-0]

        dp[i][wi] %= MOD

print((dp[h][k-1]%MOD))

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

remv = [1,1,2,3,5,8,13,21]

dp = [ [0]*w for _ in range(h+1) ]

dp[0][0] = 1

MOD = 10**9+7

for i in range(h):

    for wi in range(w):

        left = wi

        right = w-wi-1

        com = remv[left] * remv[right]

        dp[i+1][wi] += dp[i][wi]*com

        dp[i+1][wi] %= MOD

        if wi > 0:

            left = wi-1

            right = w-wi-1

            com = remv[left] * remv[right]

            dp[i+1][wi-1] += dp[i][wi]*com

            dp[i+1][wi-1] %= MOD

        if wi < w-1:

            left = wi

            right = w-(wi+1)-1

            com = remv[left] * remv[right]

            dp[i+1][wi+1] += dp[i][wi]*com

            dp[i+1][wi+1] %= MOD

print((dp[h][k-1]))

MOD = 10**9 + 7
h, w, k = list(map(int, input().split()))
patterns = [1, 1, 2, 3, 5, 8, 13, 21]
dp = [[0] * w for _ in range(h + 1)]
dp[0][0] = 1
for i in range(1, h + 1):
    for wi in range(w):
        dp[i][wi] = dp[i - 1][wi] * patterns[w - 1 - wi] * patterns[wi - 0]
        if wi > 0:
            dp[i][wi] += dp[i - 1][wi - 1] * patterns[w - 1 - wi] * patterns[wi - 1]
        if wi < w - 1:
            dp[i][wi] += dp[i - 1][wi + 1] * patterns[w - 1 - wi - 1] * patterns[wi - 0]
        dp[i][wi] %= MOD
print((dp[h][k - 1] % MOD))

h, w, k = list(map(int, input().split()))
remv = [1, 1, 2, 3, 5, 8, 13, 21]
dp = [[0] * w for _ in range(h + 1)]
dp[0][0] = 1
MOD = 10**9 + 7
for i in range(h):
    for wi in range(w):
        left = wi
        right = w - wi - 1
        com = remv[left] * remv[right]
        dp[i + 1][wi] += dp[i][wi] * com
        dp[i + 1][wi] %= MOD
        if wi > 0:
            left = wi - 1
            right = w - wi - 1
            com = remv[left] * remv[right]
            dp[i + 1][wi - 1] += dp[i][wi] * com
            dp[i + 1][wi - 1] %= MOD
        if wi < w - 1:
            left = wi
            right = w - (wi + 1) - 1
            com = remv[left] * remv[right]
            dp[i + 1][wi + 1] += dp[i][wi] * com
            dp[i + 1][wi + 1] %= MOD
print((dp[h][k - 1]))

-        dp[i][wi] = dp[i - 1][wi] * patterns[w - 1 - wi] * patterns[wi - 0]

-            dp[i][wi] += dp[i - 1][wi - 1] * patterns[w - 1 - wi] * patterns[wi - 1]

+            com = remv[left] * remv[right]

-            dp[i][wi] += dp[i - 1][wi + 1] * patterns[w - 1 - wi - 1] * patterns[wi - 0]

+            com = remv[left] * remv[right]


Input:
#from statistics import median

#import collections

#aa = collections.Counter(a) # list to list

#from itertools import combinations # (string,3) 3回

mod = 10**9 + 7

def readInts():

  return list(map(int,input().split()))

def main():

    # S: azzel

    # T: apple

    S = eval(input())

    T = eval(input())

    ok = True

    dic_s = {}

    dic_t = {}

    for i in range(len(S)):

        s = S[i]

        t = T[i]

        if s in list(dic_s.keys()):

            if dic_s[s] != t:

                ok = False

        if t in list(dic_t.keys()):

            if dic_t[t] != s:

                ok = False

        dic_s[s] = t

        dic_t[t] = s

        #print(dic_s,dic_t,sep='\n')

    if ok:

        print('Yes')

    else:

        print('No')

if __name__ == '__main__':

  main()

#from statistics import median

#import collections

#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

#from itertools import combinations # (string,3) 3回

#from collections import deque

#import collections.defaultdict(list)

#import bisect

#

#    d = m - k[i] - k[j]

#    if kk[bisect.bisect_right(kk,d) - 1] == d:

#

#

#

# pythonで無理なときは、pypyでやると正解するかも！！

#

#

mod = 10**9 + 7

def readInts():

  return list(map(int,input().split()))

def main():

    S = eval(input())

    T = eval(input())

    dic_s = {}

    dic_t = {}

    for i in range(len(S)):

        s = S[i]

        t = T[i]

        if s in dic_t:

            if dic_t[s] != t:

                print('No')

                exit()

        if t in dic_s:

            if dic_s[t] != s:

                print('No')

                exit()

        dic_t[s] = t

        dic_s[t] = s

    print('Yes')

if __name__ == '__main__':

  main()

# from statistics import median
# import collections
# aa = collections.Counter(a) # list to list
# from itertools import combinations # (string,3) 3回
mod = 10**9 + 7

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

def main():
    # S: azzel
    # T: apple
    S = eval(input())
    T = eval(input())
    ok = True
    dic_s = {}
    dic_t = {}
    for i in range(len(S)):
        s = S[i]
        t = T[i]
        if s in list(dic_s.keys()):
            if dic_s[s] != t:
                ok = False
        if t in list(dic_t.keys()):
            if dic_t[t] != s:
                ok = False
        dic_s[s] = t
        dic_t[t] = s
        # print(dic_s,dic_t,sep='\n')
    if ok:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

# from statistics import median
# import collections
# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
# from itertools import combinations # (string,3) 3回
# from collections import deque
# import collections.defaultdict(list)
# import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
mod = 10**9 + 7

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

def main():
    S = eval(input())
    T = eval(input())
    dic_s = {}
    dic_t = {}
    for i in range(len(S)):
        s = S[i]
        t = T[i]
        if s in dic_t:
            if dic_t[s] != t:
                print("No")
                exit()
        if t in dic_s:
            if dic_s[t] != s:
                print("No")
                exit()
        dic_t[s] = t
        dic_s[t] = s
    print("Yes")

if __name__ == "__main__":
    main()

-# aa = collections.Counter(a) # list to list

+# aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]

+#    if kk[bisect.bisect_right(kk,d) - 1] == d:

+# pythonで無理なときは、pypyでやると正解するかも！！


Input:
import sys

n = int(eval(input()))

if n < 357:

  print((0))

  sys.exit()

def dfs(s):

  if int(s) > n:

    return 0

  ret = 1 if all(s.count(c) > 0 for c in '753') else 0

  for c in '753':

    ret += dfs(s + c)

  return ret

print((dfs('0')))

#!/usr/bin/env python3

import sys

import itertools

def solve(N: int):

    LEN = len(str(N))

    if LEN <= 2:

        print((0))

        return

    answer = 0

    for i in range(3,LEN+1):

        for num in list(itertools.product(['3','5','7'], repeat=i)):

            if num.count('3') >= 1 and num.count('5')>=1 and num.count('7') >=1 and int(''.join(num))<=N:

                answer +=1

    print(answer)

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

    N = int(next(tokens))  # type: int

    solve(N)

if __name__ == '__main__':

    main()

import sys

n = int(eval(input()))
if n < 357:
    print((0))
    sys.exit()

def dfs(s):
    if int(s) > n:
        return 0
    ret = 1 if all(s.count(c) > 0 for c in "753") else 0
    for c in "753":
        ret += dfs(s + c)
    return ret

print((dfs("0")))

#!/usr/bin/env python3
import sys
import itertools

def solve(N: int):
    LEN = len(str(N))
    if LEN <= 2:
        print((0))
        return
    answer = 0
    for i in range(3, LEN + 1):
        for num in list(itertools.product(["3", "5", "7"], repeat=i)):
            if (
                num.count("3") >= 1
                and num.count("5") >= 1
                and num.count("7") >= 1
                and int("".join(num)) <= N
            ):
                answer += 1
    print(answer)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    solve(N)

if __name__ == "__main__":
    main()

-    ret = 1 if all(s.count(c) > 0 for c in "753") else 0

+        for num in list(itertools.product(["3", "5", "7"], repeat=i)):

+                and num.count("5") >= 1

+                and num.count("7") >= 1

+                and int("".join(num)) <= N


Input:
NM= input ().split()

N= int (NM[0])

M= int (NM[1])

if (N==M):

    print ("Yes")

else:

    print ("No")

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

print(('Yes' if a==b else 'No'))

NM = input().split()
N = int(NM[0])
M = int(NM[1])
if N == M:
    print("Yes")
else:
    print("No")

a, b = list(map(int, input().split()))
print(("Yes" if a == b else "No"))

-NM = input().split()
-N = int(NM[0])
-M = int(NM[1])
-if N == M:
-    print("Yes")
-else:
-    print("No")
+a, b = list(map(int, input().split()))
+print(("Yes" if a == b else "No"))


Input:
N,M = list(map(int, input().split()))

xs,ys,zs = [], [], []

"""

sum000 +++

sum001 ++-

sum010 +-+

sum011 +--

sum100 -++

sum101 -+-

sum110 --+

sum111 ---

"""

sum000, sum001, sum010,sum011 = [], [], [], []

sum100, sum101, sum110,sum111 = [], [], [], []

sums = [[] for i in range(8)]

for i in range(N):

    x,y,z = list(map(int, input().split()))

    sums[0].append(x+y+z)

    sums[1].append(x+y-z)

    sums[2].append(x-y+z)

    sums[3].append(x-y-z)

    sums[4].append(-x+y+z)

    sums[5].append(-x+y-z)

    sums[6].append(-x-y+z)

    sums[7].append(-x-y-z)

ans = 0

for s in sums:

    s1 = sorted(s,reverse=False)

    s2 = sorted(s,reverse=False)

    x = max(abs(sum(s1[:M])),abs(sum(s2[:M])))

    ans = max(ans,x)

print(ans)

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

"""

 xyz

0+++

1++-

2+-+

3+--

4-++

5-+-

6--+

7---

"""

dp = [[0]*N for i in range(8)]

for i in range(N):

    x,y,z = list(map(int, input().split()))

    dp[0][i] = x+y+z

    dp[1][i] = x+y-z

    dp[2][i] = x-y+z

    dp[3][i] = x-y-z

    dp[4][i] = -x+y+z

    dp[5][i] = -x+y-z

    dp[6][i] = -x-y+z

    dp[7][i] = -x-y-z

ans = 0

for i in range(8):

    sums = sorted(dp[i], reverse=True)

    ans = max(sum(sums[:M]),ans)

print(ans)

N, M = list(map(int, input().split()))
xs, ys, zs = [], [], []
"""
sum000 +++
sum001 ++-
sum010 +-+
sum011 +--
sum100 -++
sum101 -+-
sum110 --+
sum111 ---
"""
sum000, sum001, sum010, sum011 = [], [], [], []
sum100, sum101, sum110, sum111 = [], [], [], []
sums = [[] for i in range(8)]
for i in range(N):
    x, y, z = list(map(int, input().split()))
    sums[0].append(x + y + z)
    sums[1].append(x + y - z)
    sums[2].append(x - y + z)
    sums[3].append(x - y - z)
    sums[4].append(-x + y + z)
    sums[5].append(-x + y - z)
    sums[6].append(-x - y + z)
    sums[7].append(-x - y - z)
ans = 0
for s in sums:
    s1 = sorted(s, reverse=False)
    s2 = sorted(s, reverse=False)
    x = max(abs(sum(s1[:M])), abs(sum(s2[:M])))
    ans = max(ans, x)
print(ans)

N, M = list(map(int, input().split()))
"""
 xyz
0+++
1++-
2+-+
3+--
4-++
5-+-
6--+
7---
"""
dp = [[0] * N for i in range(8)]
for i in range(N):
    x, y, z = list(map(int, input().split()))
    dp[0][i] = x + y + z
    dp[1][i] = x + y - z
    dp[2][i] = x - y + z
    dp[3][i] = x - y - z
    dp[4][i] = -x + y + z
    dp[5][i] = -x + y - z
    dp[6][i] = -x - y + z
    dp[7][i] = -x - y - z
ans = 0
for i in range(8):
    sums = sorted(dp[i], reverse=True)
    ans = max(sum(sums[:M]), ans)
print(ans)


Input:
N = int(eval(input()))

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

stp = [0]*(N+1)

stp[0] = 0

for i in range(1,N):

    if H[i]<=H[i-1]:

        stp[i] = stp[i-1] +1

    else:

        stp[i] = 0

print((max(stp)))

N = int(eval(input()))

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

memo = [0]*N

for i in range(1,N):

    if h[i]<=h[i-1]:

        memo[i] = memo[i-1] + 1

print((max(memo)))

N = int(eval(input()))
H = list(map(int, input().split()))
stp = [0] * (N + 1)
stp[0] = 0
for i in range(1, N):
    if H[i] <= H[i - 1]:
        stp[i] = stp[i - 1] + 1
    else:
        stp[i] = 0
print((max(stp)))

N = int(eval(input()))
h = list(map(int, input().split()))
memo = [0] * N
for i in range(1, N):
    if h[i] <= h[i - 1]:
        memo[i] = memo[i - 1] + 1
print((max(memo)))

-H = list(map(int, input().split()))
-stp = [0] * (N + 1)
-stp[0] = 0
+h = list(map(int, input().split()))
+memo = [0] * N
-    if H[i] <= H[i - 1]:
-        stp[i] = stp[i - 1] + 1
-    else:
-        stp[i] = 0
-print((max(stp)))
+    if h[i] <= h[i - 1]:
+        memo[i] = memo[i - 1] + 1
+print((max(memo)))


Input:
from collections import deque

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

cnt = [0]*n

for i in range(n):

    d = [float('inf')]*n

    que = deque([(i, 0)])

    while que:

        idx, c = que.popleft()

        if d[idx]!=float('inf'):

            d[idx] = min(d[idx], c)

            continue

        else:

            d[idx] = min(d[idx], c)

            if idx!=0:

                que.append((idx-1, c+1))

            if idx!=n-1:

                que.append((idx+1, c+1))

            if idx==x-1:

                que.append((y-1, c+1))

            if idx==y-1:

                que.append((x-1, c+1))

    for j in range(i+1, n):

        cnt[d[j]] += 1

for c in cnt[1:]:

    print(c)

from collections import deque

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

G = [[] for _ in range(n+1)]

for i in range(1, n):

    G[i].append(i+1)

    G[i+1].append(i)

G[x].append(y)

G[y].append(x)

cost = [0]*(n+1)

for i in range(1, n+1):

    visited = [-1]*(n+1)

    que = deque([(i, 0)])

    while que:

        idx, cst = que.popleft()

        if visited[idx]!=-1:

            continue

        visited[idx] = cst

        for to in G[idx]:

            que.append((to, cst+1))

    for j in range(i, n+1):

        cost[visited[j]] += 1

for c in cost[1:-1]:

    print(c)

from collections import deque

n, x, y = list(map(int, input().split()))
cnt = [0] * n
for i in range(n):
    d = [float("inf")] * n
    que = deque([(i, 0)])
    while que:
        idx, c = que.popleft()
        if d[idx] != float("inf"):
            d[idx] = min(d[idx], c)
            continue
        else:
            d[idx] = min(d[idx], c)
            if idx != 0:
                que.append((idx - 1, c + 1))
            if idx != n - 1:
                que.append((idx + 1, c + 1))
            if idx == x - 1:
                que.append((y - 1, c + 1))
            if idx == y - 1:
                que.append((x - 1, c + 1))
    for j in range(i + 1, n):
        cnt[d[j]] += 1
for c in cnt[1:]:
    print(c)

from collections import deque

n, x, y = list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
for i in range(1, n):
    G[i].append(i + 1)
    G[i + 1].append(i)
G[x].append(y)
G[y].append(x)
cost = [0] * (n + 1)
for i in range(1, n + 1):
    visited = [-1] * (n + 1)
    que = deque([(i, 0)])
    while que:
        idx, cst = que.popleft()
        if visited[idx] != -1:
            continue
        visited[idx] = cst
        for to in G[idx]:
            que.append((to, cst + 1))
    for j in range(i, n + 1):
        cost[visited[j]] += 1
for c in cost[1:-1]:
    print(c)

-                que.append((idx - 1, c + 1))

-                que.append((idx + 1, c + 1))

-                que.append((y - 1, c + 1))

-                que.append((x - 1, c + 1))


Input:
N = int(eval(input()))

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

x = [0 for _ in range(N)]

for i in range(N):

    if i % 2 == 0:

        x[0] += A[i]

    else:

        x[0] -= A[i]

x[0] //= 2

for i in range(1, N):

    x[i] = A[i - 1] - x[i - 1]

ans = ' '.join(str(2 * X) for X in x)

print(ans)

from itertools import accumulate

N = int(eval(input()))

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

# x_1 = (A_1 - A_2 + A_3 - A_4 + ... + A_N) / 2 である

# x_2 以降は代入しながら求めればよい

ans = ' '.join(

    str(2 * x)

    for x in accumulate(

        [sum((-1)**i * A[i] for i in range(N)) // 2] + A[:-1],

        lambda acc, a: a - acc

    )

)

print(ans)

N = int(eval(input()))
A = list(map(int, input().split()))
x = [0 for _ in range(N)]
for i in range(N):
    if i % 2 == 0:
        x[0] += A[i]
    else:
        x[0] -= A[i]
x[0] //= 2
for i in range(1, N):
    x[i] = A[i - 1] - x[i - 1]
ans = " ".join(str(2 * X) for X in x)
print(ans)

from itertools import accumulate

N = int(eval(input()))
A = list(map(int, input().split()))
# x_1 = (A_1 - A_2 + A_3 - A_4 + ... + A_N) / 2 である
# x_2 以降は代入しながら求めればよい
ans = " ".join(
    str(2 * x)
    for x in accumulate(
        [sum((-1) ** i * A[i] for i in range(N)) // 2] + A[:-1], lambda acc, a: a - acc
    )
)
print(ans)

+# x_2 以降は代入しながら求めればよい

+        [sum((-1) ** i * A[i] for i in range(N)) // 2] + A[:-1], lambda acc, a: a - acc


Input:
x, k, d = list(map(int, input().split()))

x = abs(x)

div, mod = divmod(x, d)

c = div - k

if c == 0:

    ans = mod

elif c > 0:

    ans = x - d * k

else:

    if c%2 == 1: ans = d - mod

    else: ans = mod

print(ans)

x, k, d = list(map(int, input().split()))

x = abs(x)

div, mod = divmod(x, d)

c = k - div

if c <= 0:

    ans = x - d * k

else:

    if c%2 == 1: ans = d - mod

    else: ans = mod

print(ans)

x, k, d = list(map(int, input().split()))
x = abs(x)
div, mod = divmod(x, d)
c = div - k
if c == 0:
    ans = mod
elif c > 0:
    ans = x - d * k
else:
    if c % 2 == 1:
        ans = d - mod
    else:
        ans = mod
print(ans)

x, k, d = list(map(int, input().split()))
x = abs(x)
div, mod = divmod(x, d)
c = k - div
if c <= 0:
    ans = x - d * k
else:
    if c % 2 == 1:
        ans = d - mod
    else:
        ans = mod
print(ans)

-c = div - k
-if c == 0:
-    ans = mod
-elif c > 0:
+c = k - div
+if c <= 0:


Input:
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(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

#from decimal import *

S = list(eval(input()))

N = len(S)

cnt = 0

for i in range(len(S)-1):

	if S[i]==S[i+1]:

		cnt += 1

		S[min(len(S)-1, i+2)] = "_"

print((N-cnt))

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(eval(input()))

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

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

def ZIP(n): return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10 ** 9)

INF = float('inf')

mod = 10**9 + 7

#from decimal import *

S = list(eval(input())) + [""]

cnt = 0

for i in range(len(S)-1):

	if S[i]==S[i+1]:

		cnt += 1

		S[i+2] = "_"

print((len(S)-1-cnt))

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(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# from decimal import *
S = list(eval(input()))
N = len(S)
cnt = 0
for i in range(len(S) - 1):
    if S[i] == S[i + 1]:
        cnt += 1
        S[min(len(S) - 1, i + 2)] = "_"
print((N - cnt))

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(eval(input()))

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

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

def ZIP(n):
    return list(zip(*(MAP() for _ in range(n))))

sys.setrecursionlimit(10**9)
INF = float("inf")
mod = 10**9 + 7
# from decimal import *
S = list(eval(input())) + [""]
cnt = 0
for i in range(len(S) - 1):
    if S[i] == S[i + 1]:
        cnt += 1
        S[i + 2] = "_"
print((len(S) - 1 - cnt))


Input:
from collections import defaultdict

def main():

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

    d = {1: 14}

    if d.get(A, A) == d.get(B, B):

        print("Draw")

    elif d.get(A, A) > d.get(B, B):

        print("Alice")

    else:

        print("Bob")

if __name__ == '__main__':

    main()

from collections import defaultdict

def main():

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

    if A == 1:

        A = 14

    if B == 1:

        B = 14

    if A == B:

        print("Draw")

    elif A > B:

        print("Alice")

    else:

        print("Bob")

if __name__ == '__main__':

    main()

from collections import defaultdict

def main():
    A, B = list(map(int, input().split()))
    d = {1: 14}
    if d.get(A, A) == d.get(B, B):
        print("Draw")
    elif d.get(A, A) > d.get(B, B):
        print("Alice")
    else:
        print("Bob")

if __name__ == "__main__":
    main()

from collections import defaultdict

def main():
    A, B = list(map(int, input().split()))
    if A == 1:
        A = 14
    if B == 1:
        B = 14
    if A == B:
        print("Draw")
    elif A > B:
        print("Alice")
    else:
        print("Bob")

if __name__ == "__main__":
    main()


Input:
import sys

input = sys.stdin.readline

N = int(eval(input()))

A = [int(eval(input())) for _ in range(N)]

ans = A[0] - 1

P = 2

for i in range(1, N):

    if A[i] == P:

        P += 1

        continue

    ans += (A[i]-  1) // P

print(ans)

import sys

input = sys.stdin.readline

N = int(eval(input()))

A = [int(eval(input())) for _ in range(N)]

cur = 1

ans = A[0] - 1

for a in A[1:]:

    if a == cur + 1:

        cur += 1

    elif a % (cur + 1) == 0:

        ans += a // (cur + 1) - 1

    else:

        ans += a // (cur + 1)

print(ans)

import sys

input = sys.stdin.readline
N = int(eval(input()))
A = [int(eval(input())) for _ in range(N)]
ans = A[0] - 1
P = 2
for i in range(1, N):
    if A[i] == P:
        P += 1
        continue
    ans += (A[i] - 1) // P
print(ans)


Input:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,queue,copy

sys.setrecursionlimit(10**7)

inf=10**20

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 I(): return int(sys.stdin.readline())

def LS(): return sys.stdin.readline().split()

def S(): return eval(input())

def main():

  a,b=LI()

  x=max(a,b)-min(a,b)

  if x%2==1:

    return 'IMPOSSIBLE'

  return max(a,b)-x//2

# main()

print((main()))

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

sys.setrecursionlimit(10**7)

inf=10**20

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 I(): return int(sys.stdin.readline())

def LS(): return sys.stdin.readline().split()

def S(): return eval(input())

def main():

  a,b=LI()

  if a%2!=b%2:

    return 'IMPOSSIBLE'

  return (a+b)//2

# main()

print((main()))

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

sys.setrecursionlimit(10**7)
inf = 10**20
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 I():
    return int(sys.stdin.readline())

def LS():
    return sys.stdin.readline().split()

def S():
    return eval(input())

def main():
    a, b = LI()
    x = max(a, b) - min(a, b)
    if x % 2 == 1:
        return "IMPOSSIBLE"
    return max(a, b) - x // 2

# main()
print((main()))

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

sys.setrecursionlimit(10**7)
inf = 10**20
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 I():
    return int(sys.stdin.readline())

def LS():
    return sys.stdin.readline().split()

def S():
    return eval(input())

def main():
    a, b = LI()
    if a % 2 != b % 2:
        return "IMPOSSIBLE"
    return (a + b) // 2

# main()
print((main()))


Input:
# coding: utf-8

# Your code here!

import array

SIZE=300000; MOD= 998244353

#inv = array.array('q',[0]*(SIZE+1))# inv[j] = j^{-1} mod M

#fac = array.array('q',[0]*(SIZE+1))# inv[j] = j! mod M

#finv = array.array('q',[0]*(SIZE+1))# inv[j] = (j!)^{-1} mod M

inv = [0]*(SIZE+1)# inv[j] = j^{-1} mod M

fac = [0]*(SIZE+1)# inv[j] = j! mod M

finv = [0]*(SIZE+1)# inv[j] = (j!)^{-1} mod M

inv[1] = 1

fac[0] = fac[1] = 1

finv[0] = finv[1] = 1

for i in range(2,SIZE+1):

    inv[i] = MOD -(MOD//i)*inv[MOD%i]%MOD

    fac[i] = fac[i-1]*i%MOD

    finv[i]= finv[i-1]*inv[i]%MOD

def choose(n,r): # nCk mod MOD の計算

    if r < 0 or r > n:

        return 0

    else:

        return (fac[n]*finv[r]%MOD)*finv[n-r]%MOD

n,a,b,k = [int(i) for i in input().split()]

ans=0

for i in range(n+1):

    if (k-i*a)%b == 0:

        ans = (ans + choose(n,i)*choose(n,(k-i*a)//b)%MOD)%MOD

print(ans)

SIZE=300000; MOD=998244353 #ここを変更する

inv = [0]*(SIZE+1)# inv[j] = j^{-1} mod MOD

fac = [0]*(SIZE+1)# inv[j] = j! mod MOD

finv = [0]*(SIZE+1)# inv[j] = (j!)^{-1} mod MOD

inv[1] = 1

fac[0] = fac[1] = 1

finv[0] = finv[1] = 1

for i in range(2,SIZE+1):

    inv[i] = MOD -(MOD//i)*inv[MOD%i]%MOD

    fac[i] = fac[i-1]*i%MOD

    finv[i]= finv[i-1]*inv[i]%MOD

def choose(n,r): # nCk mod MOD の計算

    if r < 0 or r > n or n < 0:

        return 0

    else:

        return (fac[n]*finv[r]%MOD)*finv[n-r]%MOD

n,a,b,k = [int(i) for i in input().split()]

ans=0

for i in range(n+1):

    if (k-i*a)%b == 0:

        ans = (ans + choose(n,i)*choose(n,(k-i*a)//b)%MOD)%MOD

print(ans)

# coding: utf-8
# Your code here!
import array

SIZE = 300000
MOD = 998244353
# inv = array.array('q',[0]*(SIZE+1))# inv[j] = j^{-1} mod M
# fac = array.array('q',[0]*(SIZE+1))# inv[j] = j! mod M
# finv = array.array('q',[0]*(SIZE+1))# inv[j] = (j!)^{-1} mod M
inv = [0] * (SIZE + 1)  # inv[j] = j^{-1} mod M
fac = [0] * (SIZE + 1)  # inv[j] = j! mod M
finv = [0] * (SIZE + 1)  # inv[j] = (j!)^{-1} mod M
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE + 1):
    inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
    fac[i] = fac[i - 1] * i % MOD
    finv[i] = finv[i - 1] * inv[i] % MOD

def choose(n, r):  # nCk mod MOD の計算
    if r < 0 or r > n:
        return 0
    else:
        return (fac[n] * finv[r] % MOD) * finv[n - r] % MOD

n, a, b, k = [int(i) for i in input().split()]
ans = 0
for i in range(n + 1):
    if (k - i * a) % b == 0:
        ans = (ans + choose(n, i) * choose(n, (k - i * a) // b) % MOD) % MOD
print(ans)

SIZE = 300000
MOD = 998244353  # ここを変更する
inv = [0] * (SIZE + 1)  # inv[j] = j^{-1} mod MOD
fac = [0] * (SIZE + 1)  # inv[j] = j! mod MOD
finv = [0] * (SIZE + 1)  # inv[j] = (j!)^{-1} mod MOD
inv[1] = 1
fac[0] = fac[1] = 1
finv[0] = finv[1] = 1
for i in range(2, SIZE + 1):
    inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
    fac[i] = fac[i - 1] * i % MOD
    finv[i] = finv[i - 1] * inv[i] % MOD

def choose(n, r):  # nCk mod MOD の計算
    if r < 0 or r > n or n < 0:
        return 0
    else:
        return (fac[n] * finv[r] % MOD) * finv[n - r] % MOD

n, a, b, k = [int(i) for i in input().split()]
ans = 0
for i in range(n + 1):
    if (k - i * a) % b == 0:
        ans = (ans + choose(n, i) * choose(n, (k - i * a) // b) % MOD) % MOD
print(ans)

-# inv = array.array('q',[0]*(SIZE+1))# inv[j] = j^{-1} mod M

-# fac = array.array('q',[0]*(SIZE+1))# inv[j] = j! mod M

-fac = [0] * (SIZE + 1)  # inv[j] = j! mod M

+fac = [0] * (SIZE + 1)  # inv[j] = j! mod MOD


Input:
s = eval(input())

x = ''

for i in range(len(s)):

    if i%2 == 0:

        x += s[i:i+1]

print(x)

s = eval(input())

ans = ''

for i in range(len(s)):

    if i%2 == 0:

        ans += s[i]

print(ans)

s = eval(input())
x = ""
for i in range(len(s)):
    if i % 2 == 0:
        x += s[i : i + 1]
print(x)

s = eval(input())
ans = ""
for i in range(len(s)):
    if i % 2 == 0:
        ans += s[i]
print(ans)

-x = ""
+ans = ""
-        x += s[i : i + 1]
-print(x)
+        ans += s[i]
+print(ans)


Input:
n=int(eval(input()))

p=list(map(float,input().split()))

mid=(n+2)//2

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

dp[0][0]=1-p[0]

dp[0][1]=p[0]

for i in range(n-1):

    for j in range(n+1):

        if dp[i][j]!=0:

            #表が出るとき

            dp[i+1][j+1]+=dp[i][j]*p[i+1]

            #裏

            dp[i+1][j]+=dp[i][j]*(1-p[i+1])

print((sum(dp[-1][mid:])))

n=int(eval(input()))

p=list(map(float,input().split()))

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

for i in range(n):

    for j in range(n+1):

        if i==0:

            dp[0][0]=1-p[i]

            dp[0][1]=p[i]

        else:

            #表が出る

            if dp[i-1][j-1]!=0:

                dp[i][j]+=dp[i-1][j-1]*p[i]

            #裏

                dp[i][j-1]+=dp[i-1][j-1]*(1-p[i])

print((sum(dp[-1][int(n/2)+1:])))

#print(dp)

n = int(eval(input()))
p = list(map(float, input().split()))
dp = [[0] * (n + 1) for i in range(n)]
for i in range(n):
    for j in range(n + 1):
        if i == 0:
            dp[0][0] = 1 - p[i]
            dp[0][1] = p[i]
        else:
            # 表が出る
            if dp[i - 1][j - 1] != 0:
                dp[i][j] += dp[i - 1][j - 1] * p[i]
                # 裏
                dp[i][j - 1] += dp[i - 1][j - 1] * (1 - p[i])
print((sum(dp[-1][int(n / 2) + 1 :])))
# print(dp)

-            # 表が出るとき

+            # 表が出る


Input:
n = int(eval(input()))

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

a = list(enumerate(a, 1))

a = sorted(a, key=lambda x:x[1])

res = [a[i][0] for i in range(n)]

print((*res))

n=int(input())

arr=[int(i) for i in input().split()]

dic={}

for i in range(n):

    dic[arr[i]]=i+1

ans=[]

for i in range(1,n+1):

    ans.append(dic[i])

for i in ans:

    print(i,end=" ")

n = int(eval(input()))
a = list(map(int, input().split()))
a = list(enumerate(a, 1))
a = sorted(a, key=lambda x: x[1])
res = [a[i][0] for i in range(n)]
print((*res))

n = int(input())
arr = [int(i) for i in input().split()]
dic = {}
for i in range(n):
    dic[arr[i]] = i + 1
ans = []
for i in range(1, n + 1):
    ans.append(dic[i])
for i in ans:
    print(i, end=" ")

+arr = [int(i) for i in input().split()]


Input:
# ABC100 C - *3 or /2

N = int(eval(input()))

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

ans = 0

for i in range(N):

    x = 0

    t = 0

    x = A[i]

    while x%2==0:

        x = x//2

        t += 1

    ans += t

print(ans)

def count(x):

    cnt=0

    while x!=0:

        if x%2==0:

            x//=2

            cnt+=1

        else:

            break

    return cnt

n=int(eval(input()))

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

ans=0

for aa in a:

    if aa%2==0:

        ans+=count(aa)

print(ans)

# ABC100 C - *3 or /2
N = int(eval(input()))
A = list(map(int, input().split()))
ans = 0
for i in range(N):
    x = 0
    t = 0
    x = A[i]
    while x % 2 == 0:
        x = x // 2
        t += 1
    ans += t
print(ans)

def count(x):
    cnt = 0
    while x != 0:
        if x % 2 == 0:
            x //= 2
            cnt += 1
        else:
            break
    return cnt

n = int(eval(input()))
a = list(map(int, input().split()))
ans = 0
for aa in a:
    if aa % 2 == 0:
        ans += count(aa)
print(ans)

-# ABC100 C - *3 or /2
-N = int(eval(input()))
-A = list(map(int, input().split()))
+def count(x):
+    cnt = 0
+    while x != 0:
+        if x % 2 == 0:
+            x //= 2
+            cnt += 1
+        else:
+            break
+    return cnt
+
+
+n = int(eval(input()))
+a = list(map(int, input().split()))
-for i in range(N):
-    x = 0
-    t = 0
-    x = A[i]
-    while x % 2 == 0:
-        x = x // 2
-        t += 1
-    ans += t
+for aa in a:
+    if aa % 2 == 0:
+        ans += count(aa)


Input:
N,M = list(map(int,input().split()))

X = sorted(list(map(int,input().split())))

D = sorted([X[n+1]-X[n] for n in range(M-1)])

if M<=N:

  print((0))

else:

  print((sum(D[:M-N])))

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

X = sorted(map(int,input().split()))

D = sorted(x2-x1 for x1,x2 in zip(X,X[1:]))[::-1]

print((sum(D[N-1:])))

N, M = list(map(int, input().split()))
X = sorted(list(map(int, input().split())))
D = sorted([X[n + 1] - X[n] for n in range(M - 1)])
if M <= N:
    print((0))
else:
    print((sum(D[: M - N])))

N, M = list(map(int, input().split()))
X = sorted(map(int, input().split()))
D = sorted(x2 - x1 for x1, x2 in zip(X, X[1:]))[::-1]
print((sum(D[N - 1 :])))

-X = sorted(list(map(int, input().split())))

-D = sorted([X[n + 1] - X[n] for n in range(M - 1)])


Input:
ABC = list(map(int, input().split()))

if ABC.count(5) == 2 and ABC.count(7):

    print('YES')

else:

    print('NO')

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

if ABC.count(5) == 2 and ABC.count(7) == 1:

    print('YES')

else:

    print('NO')

ABC = list(map(int, input().split()))
if ABC.count(5) == 2 and ABC.count(7):
    print("YES")
else:
    print("NO")

ABC = list(map(int, input().split()))
if ABC.count(5) == 2 and ABC.count(7) == 1:
    print("YES")
else:
    print("NO")

+if ABC.count(5) == 2 and ABC.count(7) == 1:


Input:
A, B, X = list(map(int, input().split()))

print(("YES" if A <= X and X <= A+B else "NO"))

A, B, X = list(map(int, input().split()))

print(("YES" if A <= X <= A+B else "NO"))

A, B, X = list(map(int, input().split()))
print(("YES" if A <= X and X <= A + B else "NO"))

A, B, X = list(map(int, input().split()))
print(("YES" if A <= X <= A + B else "NO"))

-print(("YES" if A <= X and X <= A + B else "NO"))

+print(("YES" if A <= X <= A + B else "NO"))


Input:
import sys

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

sys.setrecursionlimit(10 ** 7)

n = int(readline())

s = eval(input())

rgb = [0, 0, 0]

for i in range(n):

    if s[i] == 'R':

        rgb[0] += 1

    elif s[i] == 'G':

        rgb[1] += 1

    else:

        rgb[2] += 1

ans = rgb[0] * rgb[1] * rgb[2]

for i in range(n):

    for j in range(i + 1, n):

        k = 2 * j - i

        if k >= n:

            break

        if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:

            ans -= 1

print(ans)

import sys

read = sys.stdin.buffer.read

readline = sys.stdin.buffer.readline

readlines = sys.stdin.buffer.readlines

sys.setrecursionlimit(10 ** 7)

n = int(readline())

s = readline().rstrip().decode()

ans = s.count('R') * s.count('G') * s.count('B')

for i, si in enumerate(s):

    for j, sj in enumerate(s[i + 1:]):

        k = 2 * (j + 1) + i

        if k >= n:

            break

        if si != sj and si != s[k] and sj != s[k]:

            ans -= 1

print(ans)

import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**7)
n = int(readline())
s = eval(input())
rgb = [0, 0, 0]
for i in range(n):
    if s[i] == "R":
        rgb[0] += 1
    elif s[i] == "G":
        rgb[1] += 1
    else:
        rgb[2] += 1
ans = rgb[0] * rgb[1] * rgb[2]
for i in range(n):
    for j in range(i + 1, n):
        k = 2 * j - i
        if k >= n:
            break
        if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:
            ans -= 1
print(ans)

import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**7)
n = int(readline())
s = readline().rstrip().decode()
ans = s.count("R") * s.count("G") * s.count("B")
for i, si in enumerate(s):
    for j, sj in enumerate(s[i + 1 :]):
        k = 2 * (j + 1) + i
        if k >= n:
            break
        if si != sj and si != s[k] and sj != s[k]:
            ans -= 1
print(ans)

+ans = s.count("R") * s.count("G") * s.count("B")

+    for j, sj in enumerate(s[i + 1 :]):

-        if s[i] != s[j] and s[j] != s[k] and s[i] != s[k]:

+        if si != sj and si != s[k] and sj != s[k]:


Input:
N = int(eval(input()))

n, p, score = N, 2, 0

while p ** 2 <= N:

  e = 1

  while n % (p ** e) == 0:

    n //= (p ** e)

    score += 1

    e += 1

  else:

    while n % p == 0:

      n //= p

    p += 1

else:

  if n != 1:

    score += 1

print(score)

N = int(eval(input()))

n, p, score = N, 2, 0

while p ** 2 <= N:

  e = 1

  while n % (p ** e) == 0:

    n //= (p ** e)

    score += 1

    e += 1

  else:

    while n % p == 0:

      n //= p

    p = p + 1 if p == 2 else p + 2

else:

  if n != 1:

    score += 1

print(score)

N = int(eval(input()))
n, p, score = N, 2, 0
while p**2 <= N:
    e = 1
    while n % (p**e) == 0:
        n //= p**e
        score += 1
        e += 1
    else:
        while n % p == 0:
            n //= p
        p += 1
else:
    if n != 1:
        score += 1
print(score)

N = int(eval(input()))
n, p, score = N, 2, 0
while p**2 <= N:
    e = 1
    while n % (p**e) == 0:
        n //= p**e
        score += 1
        e += 1
    else:
        while n % p == 0:
            n //= p
        p = p + 1 if p == 2 else p + 2
else:
    if n != 1:
        score += 1
print(score)


Input:
from collections import Counter

import sys

input = sys.stdin.buffer.readline

ans = {}

def main():

    n = int(eval(input()))

    for i in range(n):

        dic = {}

        for a in input().strip():

            if a in dic:

                dic[a] += 1

            else:

                dic[a] = 1

        dic2 = tuple(sorted(dic.items()))

        #print(dic2)

        tmp = ""

        for k, v in dic2:

            tmp += str(k) + str(v)

        if tmp in ans:

            ans[tmp] += 1

        else:

            ans[tmp] = 1

    su = 0

    for vv in list(ans.values()):

        su += vv * (vv -1) // 2

    print(su)

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():

    n = int(eval(input()))

    dic = {}

    for i in range(n):

        a = ''.join(sorted(input().rstrip()))

        if a in dic:

            dic[a] += 1

        else:

            dic[a] = 1

    su = 0

    for v in list(dic.values()):

        su += v * (v - 1) // 2

    print(su)

if __name__ == '__main__':

    main()

from collections import Counter
import sys

input = sys.stdin.buffer.readline
ans = {}

def main():
    n = int(eval(input()))
    for i in range(n):
        dic = {}
        for a in input().strip():
            if a in dic:
                dic[a] += 1
            else:
                dic[a] = 1
        dic2 = tuple(sorted(dic.items()))
        # print(dic2)
        tmp = ""
        for k, v in dic2:
            tmp += str(k) + str(v)
        if tmp in ans:
            ans[tmp] += 1
        else:
            ans[tmp] = 1
    su = 0
    for vv in list(ans.values()):
        su += vv * (vv - 1) // 2
    print(su)

if __name__ == "__main__":
    main()

import sys

input = sys.stdin.readline

def main():
    n = int(eval(input()))
    dic = {}
    for i in range(n):
        a = "".join(sorted(input().rstrip()))
        if a in dic:
            dic[a] += 1
        else:
            dic[a] = 1
    su = 0
    for v in list(dic.values()):
        su += v * (v - 1) // 2
    print(su)

if __name__ == "__main__":
    main()

-        dic2 = tuple(sorted(dic.items()))

+        a = "".join(sorted(input().rstrip()))


Input:
from math import gcd

from functools import lru_cache

from itertools import combinations

a = int(eval(input()))

def main():

    for i in range(1, a+1):

        for j in range(i, a+1):

            for k in range(j, a+1):

                x = len({i, j, k})

                if x == 1:

                    x = 1

                elif x == 2:

                    x = 3

                else:

                    x = 6

                yield gcd(gcd(i, j), k) * x

print((sum(main())))

from math import gcd

a = int(eval(input()))

def main():

    for i in range(1, a+1):

        for j in range(i, a+1):

            ab = gcd(i, j)

            for k in range(j, a+1):

                x = len({i, j, k})

                if x == 1:

                    x = 1

                elif x == 2:

                    x = 3

                else:

                    x = 6

                yield gcd(ab, k) * x

print((sum(main())))

from math import gcd
from functools import lru_cache
from itertools import combinations

a = int(eval(input()))

def main():
    for i in range(1, a + 1):
        for j in range(i, a + 1):
            for k in range(j, a + 1):
                x = len({i, j, k})
                if x == 1:
                    x = 1
                elif x == 2:
                    x = 3
                else:
                    x = 6
                yield gcd(gcd(i, j), k) * x

print((sum(main())))

from math import gcd

a = int(eval(input()))

def main():
    for i in range(1, a + 1):
        for j in range(i, a + 1):
            ab = gcd(i, j)
            for k in range(j, a + 1):
                x = len({i, j, k})
                if x == 1:
                    x = 1
                elif x == 2:
                    x = 3
                else:
                    x = 6
                yield gcd(ab, k) * x

print((sum(main())))

-                yield gcd(gcd(i, j), k) * x


Input:
#coding:utf-8

inf = 1000000

n = int(eval(input()))

M = [[inf for i in range(n)] for j in range(n)]

vwMtrx = []

for i in range(n):

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

    u = data[0]

    k = data[1]

    col = []

    for j in range(0,2*k,2):

        v, w = data[j+2], data[j+3]

        M[u][v] = w

        col.append([v,w])

    vwMtrx.append(col)

def dijkstra(s):

    color = ["white" for i in range(n)]

    d = [inf for i in range(n)]

    p = [-1 for i in range(n)]

    d[s] = 0

    Q = [[s,0]]

    while Q != []:

        u = min(Q, key=lambda x:x[1])

        Q = [List for List in Q if List != u]

        u = u[0]

        color[u] = "black"

        vwList = vwMtrx[u]

        for vw in vwList:

            v,w = vw[0],vw[1]

            if color[v] != "black" and M[u][v] != inf:

                if d[u] + M[u][v] < d[v]:

                    d[v] = d[u] + M[u][v]

                    p[v] = u

                    color[v] = "gray"

                    Q.append([v, d[v]])

    return d

dList = dijkstra(0)

for i, d in enumerate(dList):

    print((i,d))

#coding: utf-8

inf = 1000000000

def dijkstra(s):

    d = [inf for i in range(n)]

    color = ["white" for i in range(n)]

    p = [-1 for i in range(n)]

    d[s] = 0

    while True:

        mincost = inf

        for i in range(n):

            if color[i] != "black" and d[i] < mincost:

                mincost = d[i]

                u = i

        if mincost == inf:

            break

        color[u] = "black"

        for v in range(n):

            if color[v] != "black" and mtrx[u][v] != False:

                if d[u] + mtrx[u][v] < d[v]:

                    d[v] = d[u] + mtrx[u][v]

                    p[v] = u

                    color[v] = "gray"

    return d

n = int(eval(input()))

mtrx = [[False for j in range(n)] for i in range(n)]

for i in range(n):

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

    k = data[1]

    for num in range(k):

        mtrx[i][data[2+2*num]] = data[2+2*num+1]

d = dijkstra(0)

for i, num in enumerate(d):

    print((i,num))

# coding:utf-8
inf = 1000000
n = int(eval(input()))
M = [[inf for i in range(n)] for j in range(n)]
vwMtrx = []
for i in range(n):
    data = list(map(int, input().split()))
    u = data[0]
    k = data[1]
    col = []
    for j in range(0, 2 * k, 2):
        v, w = data[j + 2], data[j + 3]
        M[u][v] = w
        col.append([v, w])
    vwMtrx.append(col)

def dijkstra(s):
    color = ["white" for i in range(n)]
    d = [inf for i in range(n)]
    p = [-1 for i in range(n)]
    d[s] = 0
    Q = [[s, 0]]
    while Q != []:
        u = min(Q, key=lambda x: x[1])
        Q = [List for List in Q if List != u]
        u = u[0]
        color[u] = "black"
        vwList = vwMtrx[u]
        for vw in vwList:
            v, w = vw[0], vw[1]
            if color[v] != "black" and M[u][v] != inf:
                if d[u] + M[u][v] < d[v]:
                    d[v] = d[u] + M[u][v]
                    p[v] = u
                    color[v] = "gray"
                    Q.append([v, d[v]])
    return d

dList = dijkstra(0)
for i, d in enumerate(dList):
    print((i, d))

# coding: utf-8
inf = 1000000000

def dijkstra(s):
    d = [inf for i in range(n)]
    color = ["white" for i in range(n)]
    p = [-1 for i in range(n)]
    d[s] = 0
    while True:
        mincost = inf
        for i in range(n):
            if color[i] != "black" and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == inf:
            break
        color[u] = "black"
        for v in range(n):
            if color[v] != "black" and mtrx[u][v] != False:
                if d[u] + mtrx[u][v] < d[v]:
                    d[v] = d[u] + mtrx[u][v]
                    p[v] = u
                    color[v] = "gray"
    return d

n = int(eval(input()))
mtrx = [[False for j in range(n)] for i in range(n)]
for i in range(n):
    data = list(map(int, input().split()))
    k = data[1]
    for num in range(k):
        mtrx[i][data[2 + 2 * num]] = data[2 + 2 * num + 1]
d = dijkstra(0)
for i, num in enumerate(d):
    print((i, num))

-M = [[inf for i in range(n)] for j in range(n)]

-    data = list(map(int, input().split()))

-        v, w = data[j + 2], data[j + 3]

-        Q = [List for List in Q if List != u]

+            if color[i] != "black" and d[i] < mincost:

-            if color[v] != "black" and M[u][v] != inf:

+            if color[v] != "black" and mtrx[u][v] != False:

+                if d[u] + mtrx[u][v] < d[v]:

-                    Q.append([v, d[v]])

+mtrx = [[False for j in range(n)] for i in range(n)]

+    data = list(map(int, input().split()))


Input:
import math

def combination(n, k):

    return math.factorial(n) // math.factorial(k) // math.factorial(n - k)

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

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

gu = 0

ki = 0

for i in t:

    if i%2==0:

        gu += 1

    else:

        ki += 1

gukumi = 0

kikumi = 0

for i in range(1,gu+1):

    gukumi += combination(gu,i)

if p == 0:

    for i in range(2,ki+1,2):

        kikumi += combination(ki,i)

    ans = kikumi+1+gukumi

else:

    for i in range(1,ki+1,2):

        kikumi += combination(ki,i)

    ans = kikumi

ans += gukumi*kikumi

print(ans)

import math

def combination(n, k):

    return math.factorial(n) // math.factorial(k) // math.factorial(n - k)

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

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

kisu = 0

gusu = 0

for a in A:

    if a%2 == 0:

        gusu += 1

    else:

        kisu += 1

sum_gu = 2**gusu

if P%2==0:

    sum_ki = 0

    for i in range(2,kisu+1, 2):

        sum_ki += combination(kisu, i)

    sum_ki *= sum_gu

    print((sum_gu+sum_ki))

else:

    sum_ki = 0

    for i in range(1,kisu+1, 2):

        sum_ki += combination(kisu, i)

    print((sum_gu*sum_ki))

import math

def combination(n, k):
    return math.factorial(n) // math.factorial(k) // math.factorial(n - k)

n, p = list(map(int, input().split()))
t = list(map(int, input().split()))
gu = 0
ki = 0
for i in t:
    if i % 2 == 0:
        gu += 1
    else:
        ki += 1
gukumi = 0
kikumi = 0
for i in range(1, gu + 1):
    gukumi += combination(gu, i)
if p == 0:
    for i in range(2, ki + 1, 2):
        kikumi += combination(ki, i)
    ans = kikumi + 1 + gukumi
else:
    for i in range(1, ki + 1, 2):
        kikumi += combination(ki, i)
    ans = kikumi
ans += gukumi * kikumi
print(ans)

import math

def combination(n, k):
    return math.factorial(n) // math.factorial(k) // math.factorial(n - k)

N, P = list(map(int, input().split()))
A = list(map(int, input().split()))
kisu = 0
gusu = 0
for a in A:
    if a % 2 == 0:
        gusu += 1
    else:
        kisu += 1
sum_gu = 2**gusu
if P % 2 == 0:
    sum_ki = 0
    for i in range(2, kisu + 1, 2):
        sum_ki += combination(kisu, i)
    sum_ki *= sum_gu
    print((sum_gu + sum_ki))
else:
    sum_ki = 0
    for i in range(1, kisu + 1, 2):
        sum_ki += combination(kisu, i)
    print((sum_gu * sum_ki))

-n, p = list(map(int, input().split()))
-t = list(map(int, input().split()))
-gu = 0
-ki = 0
-for i in t:
-    if i % 2 == 0:
-        gu += 1
+N, P = list(map(int, input().split()))
+A = list(map(int, input().split()))
+kisu = 0
+gusu = 0
+for a in A:
+    if a % 2 == 0:
+        gusu += 1
-        ki += 1
-gukumi = 0
-kikumi = 0
-for i in range(1, gu + 1):
-    gukumi += combination(gu, i)
-if p == 0:
-    for i in range(2, ki + 1, 2):
-        kikumi += combination(ki, i)
-    ans = kikumi + 1 + gukumi
+        kisu += 1
+sum_gu = 2**gusu
+if P % 2 == 0:
+    sum_ki = 0
+    for i in range(2, kisu + 1, 2):
+        sum_ki += combination(kisu, i)
+    sum_ki *= sum_gu
+    print((sum_gu + sum_ki))
-    for i in range(1, ki + 1, 2):
-        kikumi += combination(ki, i)
-    ans = kikumi
-ans += gukumi * kikumi
-print(ans)
+    sum_ki = 0
+    for i in range(1, kisu + 1, 2):
+        sum_ki += combination(kisu, i)
+    print((sum_gu * sum_ki))


Input:
n = int(eval(input()))

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

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

cnt, nega, posi = 0, 0, []

for x, y in zip(a, b):

    if x < y:

        nega += y - x

        cnt += 1

    else:

        posi.append(x - y)

if nega > 0:

    posi.sort(reverse=True)

    for i, x in enumerate(posi):

        nega -= x

        if nega <= 0:

            cnt += i + 1

            break

    else:

        cnt = -1

print(cnt)

def main():

    n = int(eval(input()))

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

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

    cnt, nega, posi = 0, 0, []

    for x, y in zip(a, b):

        if x < y:

            nega += y - x

            cnt += 1

        else:

            posi.append(x - y)

    if sum(posi) - nega < 0:

        print((-1))

        exit()

    posi.sort(reverse=True)

    i = 0

    while nega > 0:

        nega -= posi[i]

        cnt += 1

        i += 1

    print(cnt)

if __name__ == "__main__":

    main()

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

+    b = list(map(int, input().split()))


Input:
a = ""

for s in eval(input()):

  if s=="B":

    if len(a)!=0:

      a=a[:-1]

  else:

    a+=s

print(a)

a = ""

for s in eval(input()):

  if s=="B":

    a=a[:-1]

  else:

    a+=s

print(a)

a = ""
for s in eval(input()):
    if s == "B":
        if len(a) != 0:
            a = a[:-1]
    else:
        a += s
print(a)

a = ""
for s in eval(input()):
    if s == "B":
        a = a[:-1]
    else:
        a += s
print(a)