Input:
# coding: utf-8

import sys

import numpy as np

sr = lambda: sys.stdin.readline().rstrip()

ir = lambda: int(sr())

lr = lambda: list(map(int, sr().split()))

MOD = 998244353

N, A, B, K = lr()

answer = 0

# A * x + B * y = K

# nCx * nCy

def F(x, y):

    return comb[x] * comb[y]

def cumprod(arr, MOD):

    L = len(arr); Lsq = int(L**.5+1)

    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)

    for n in range(1, Lsq):

        arr[:, n] *= arr[:, n-1]; arr[:, n] %= MOD

    for n in range(1, Lsq):

        arr[n] *= arr[n-1, -1]; arr[n] %= MOD

    return arr.ravel()[:L]

def make_fact(U, MOD):

    x = np.arange(U, dtype=np.int64); x[0] = 1

    fact = cumprod(x, MOD)

    x = np.arange(U, 0, -1, dtype=np.int64); x[0] = pow(int(fact[-1]), MOD-2, MOD)

    fact_inv = cumprod(x, MOD)[::-1]

    return fact, fact_inv

U = N + 1 # 階乗テーブルの上限

fact, fact_inv = make_fact(U, MOD)

fact_N = fact[N]

comb = fact_N * fact_inv % MOD * fact_inv[::-1] % MOD

for x in range(N+1):

    temp = K-A*x

    q, r = divmod(temp, B)

    if r != 0:

        continue

    if q > N:

        continue

    if q < 0:

        break

    answer += F(x, q)

    answer %= MOD

print((answer % MOD))

# coding: utf-8

import sys

import numpy as np

sr = lambda: sys.stdin.readline().rstrip()

ir = lambda: int(sr())

lr = lambda: list(map(int, sr().split()))

MOD = 998244353

N, A, B, K = lr()

answer = 0

# A * x + B * y = K

# nCx * nCy

def F(x, y):

    return comb[x] * comb[y] % MOD

def cumprod(arr, MOD):

    L = len(arr); Lsq = int(L**.5+1)

    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)

    for n in range(1, Lsq):

        arr[:, n] *= arr[:, n-1]; arr[:, n] %= MOD

    for n in range(1, Lsq):

        arr[n] *= arr[n-1, -1]; arr[n] %= MOD

    return arr.ravel()[:L]

def make_fact(U, MOD):

    x = np.arange(U, dtype=np.int64); x[0] = 1

    fact = cumprod(x, MOD)

    x = np.arange(U, 0, -1, dtype=np.int64); x[0] = pow(int(fact[-1]), MOD-2, MOD)

    fact_inv = cumprod(x, MOD)[::-1]

    return fact, fact_inv

U = N + 1 # 階乗テーブルの上限

fact, fact_inv = make_fact(U, MOD)

fact_N = fact[N]

comb = fact_N * fact_inv % MOD * fact_inv[::-1] % MOD

for x in range(N+1):

    temp = K-A*x

    q, r = divmod(temp, B)

    if r != 0:

        continue

    if q > N:

        continue

    if q < 0:

        break

    answer += F(x, q)

print((answer % MOD))

# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 998244353
N, A, B, K = lr()
answer = 0
# A * x + B * y = K
# nCx * nCy
def F(x, y):
    return comb[x] * comb[y]

def cumprod(arr, MOD):
    L = len(arr)
    Lsq = int(L**0.5 + 1)
    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        arr[:, n] *= arr[:, n - 1]
        arr[:, n] %= MOD
    for n in range(1, Lsq):
        arr[n] *= arr[n - 1, -1]
        arr[n] %= MOD
    return arr.ravel()[:L]

def make_fact(U, MOD):
    x = np.arange(U, dtype=np.int64)
    x[0] = 1
    fact = cumprod(x, MOD)
    x = np.arange(U, 0, -1, dtype=np.int64)
    x[0] = pow(int(fact[-1]), MOD - 2, MOD)
    fact_inv = cumprod(x, MOD)[::-1]
    return fact, fact_inv

U = N + 1  # 階乗テーブルの上限
fact, fact_inv = make_fact(U, MOD)
fact_N = fact[N]
comb = fact_N * fact_inv % MOD * fact_inv[::-1] % MOD
for x in range(N + 1):
    temp = K - A * x
    q, r = divmod(temp, B)
    if r != 0:
        continue
    if q > N:
        continue
    if q < 0:
        break
    answer += F(x, q)
    answer %= MOD
print((answer % MOD))

# coding: utf-8
import sys
import numpy as np

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
MOD = 998244353
N, A, B, K = lr()
answer = 0
# A * x + B * y = K
# nCx * nCy
def F(x, y):
    return comb[x] * comb[y] % MOD

def cumprod(arr, MOD):
    L = len(arr)
    Lsq = int(L**0.5 + 1)
    arr = np.resize(arr, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        arr[:, n] *= arr[:, n - 1]
        arr[:, n] %= MOD
    for n in range(1, Lsq):
        arr[n] *= arr[n - 1, -1]
        arr[n] %= MOD
    return arr.ravel()[:L]

def make_fact(U, MOD):
    x = np.arange(U, dtype=np.int64)
    x[0] = 1
    fact = cumprod(x, MOD)
    x = np.arange(U, 0, -1, dtype=np.int64)
    x[0] = pow(int(fact[-1]), MOD - 2, MOD)
    fact_inv = cumprod(x, MOD)[::-1]
    return fact, fact_inv

U = N + 1  # 階乗テーブルの上限
fact, fact_inv = make_fact(U, MOD)
fact_N = fact[N]
comb = fact_N * fact_inv % MOD * fact_inv[::-1] % MOD
for x in range(N + 1):
    temp = K - A * x
    q, r = divmod(temp, B)
    if r != 0:
        continue
    if q > N:
        continue
    if q < 0:
        break
    answer += F(x, q)
print((answer % MOD))

-    return comb[x] * comb[y]
+    return comb[x] * comb[y] % MOD
-    answer %= MOD


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

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

for k in range(41):

    B = [0] * N

    for i, a in enumerate(A):

        l = max(0, i - a)

        r = min(N - 1, i + a)

        B[l] += 1

        if r + 1 < N: B[r + 1] -= 1

    for i in range(1, N): B[i] += B[i-1]

    A = B

    if k == K - 1: break

print((*A))

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

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

for _ in range(min(K, 50)):

    counter = [0] * (N+2)

    for i, a in enumerate(A, 1):

        counter[max(0, i - a)] += 1

        counter[min(N + 1, i + a + 1)] += -1

    for i in range(1, len(counter) - 1):

        counter[i] += counter[i-1]

    A = counter[1:N+1]

print((*A))

N, K = list(map(int, input().split()))
(*A,) = list(map(int, input().split()))
for k in range(41):
    B = [0] * N
    for i, a in enumerate(A):
        l = max(0, i - a)
        r = min(N - 1, i + a)
        B[l] += 1
        if r + 1 < N:
            B[r + 1] -= 1
    for i in range(1, N):
        B[i] += B[i - 1]
    A = B
    if k == K - 1:
        break
print((*A))

N, K = list(map(int, input().split()))
(*A,) = list(map(int, input().split()))
for _ in range(min(K, 50)):
    counter = [0] * (N + 2)
    for i, a in enumerate(A, 1):
        counter[max(0, i - a)] += 1
        counter[min(N + 1, i + a + 1)] += -1
    for i in range(1, len(counter) - 1):
        counter[i] += counter[i - 1]
    A = counter[1 : N + 1]
print((*A))

+    for i in range(1, len(counter) - 1):


Input:
# AOJ 0522: JOI and IOI

# Python3 2018.6.30 bal4u

import re

match = re.findall(r'[0-9]+', 'xxxx1aaaa22cc333ssss')

while True:

	try: s = input()

	except: break

	joi = ioi = 0

	for i in range(len(s)-2):

		if s[i+1] == 'O' and s[i+2] == 'I':

			if s[i] == 'J': joi += 1

			if s[i] == 'I': ioi += 1

	print(joi, ioi, sep='\n')

# AOJ 0522: JOI and IOI

# Python3 2018.6.30 bal4u

while True:

	try: s = input()

	except: break

	c = [s[i:i+3] for i in range(len(s)-2)]

	print(*[c.count(a) for a in ["JOI", "IOI"]], sep='\n')

# AOJ 0522: JOI and IOI
# Python3 2018.6.30 bal4u
import re

match = re.findall(r"[0-9]+", "xxxx1aaaa22cc333ssss")
while True:
    try:
        s = input()
    except:
        break
    joi = ioi = 0
    for i in range(len(s) - 2):
        if s[i + 1] == "O" and s[i + 2] == "I":
            if s[i] == "J":
                joi += 1
            if s[i] == "I":
                ioi += 1
    print(joi, ioi, sep="\n")

# AOJ 0522: JOI and IOI
# Python3 2018.6.30 bal4u
while True:
    try:
        s = input()
    except:
        break
    c = [s[i : i + 3] for i in range(len(s) - 2)]
    print(*[c.count(a) for a in ["JOI", "IOI"]], sep="\n")

-match = re.findall(r"[0-9]+", "xxxx1aaaa22cc333ssss")

+    c = [s[i : i + 3] for i in range(len(s) - 2)]

+    print(*[c.count(a) for a in ["JOI", "IOI"]], sep="\n")


Input:
from itertools import accumulate

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

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

btfl = []

for i in range(0, n):

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

        btfl.append(a[j] - a[i])

# 解説AC

ans = 0

for i in range(50)[::-1]:

    num, cnt = ans + pow(2, i), 0

    for b in btfl:

        if num == num & b:

            cnt += 1

    if cnt >= k:

        ans = num

print(ans)

from itertools import accumulate

def main():

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

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

    btfl = []

    for i in range(0, n):

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

            btfl.append(a[j] - a[i])

    # 解説AC

    ans = 0

    for i in range(50)[::-1]:

        num, cnt = ans + pow(2, i), 0

        for b in btfl:

            if num == num & b:

                cnt += 1

        if cnt >= k:

            ans = num

    print(ans)

if __name__ == '__main__':

    main()

from itertools import accumulate

def main():
    n, k = list(map(int, input().split()))
    a = [0] + list(accumulate(list(map(int, input().split()))))
    btfl = []
    for i in range(0, n):
        for j in range(i + 1, n + 1):
            btfl.append(a[j] - a[i])
    # 解説AC
    ans = 0
    for i in range(50)[::-1]:
        num, cnt = ans + pow(2, i), 0
        for b in btfl:
            if num == num & b:
                cnt += 1
        if cnt >= k:
            ans = num
    print(ans)

if __name__ == "__main__":
    main()

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

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

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


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

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

S = sum(map(abs,A))

if all([a>0 for a in A]):

    print((S-2*min(A)))

    A = sorted(A)

    B = [A[0]]

    for i in range(1,N):

        B.append(B[-1]-A[i])

    for i in range(N-2):

        print((B[i],A[i+1]))

    print((A[N-1],B[N-2]))

elif all([a<0 for a in A]):

    print((S+2*max(A)))

    A = sorted(A)

    B = [A[-1]]

    for i in range(N-1):

        B.append(B[-1]-A[i])

    for i in range(N-1):

        print((B[i],A[i]))

else:

    print(S)

    A = sorted(A)

    B = [A[0]]

    for i in range(N):

        if N-1-2-i<0 or A[-2-i]<0:

            print((A[-1-i],B[-1]))

            B.append(A[-1-i]-B[-1])

            break

        print((B[-1],A[-1-i]))

        B.append(B[-1]-A[-1-i])

    C = [B[-1]]

    for i in range(1,N):

        if A[i]>=0:

            break

        print((C[-1],A[i]))

        C.append(C[-1]-A[i])

N = int(eval(input()))

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

A.sort()

S = sum(A)

if A[0] >= 0:

    print((S - A[0] * 2))

    tmp = A[0]

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

        print((tmp, A[i]))

        tmp -= A[i]

    print((A[-1], tmp))

elif A[-1] <= 0:

    print((-S + A[-1] * 2))

    tmp = A[-1]

    for i in range(1, N):

        print((tmp, A[~i]))

        tmp -= A[~i]

else:

    op = []

    tmp1 = A[-1]

    i = 1

    while A[i] < 0:

        op.append((tmp1, A[i]))

        tmp1 -= A[i]

        i += 1

    tmp2 = A[0]

    i = 1

    while A[~i] >= 0:

        op.append((tmp2, A[~i]))

        tmp2 -= A[~i]

        i += 1

    print((tmp1 - tmp2))

    for x, y in op:

        print((x, y))

    print((tmp1, tmp2))

N = int(eval(input()))
A = list(map(int, input().split()))
S = sum(map(abs, A))
if all([a > 0 for a in A]):
    print((S - 2 * min(A)))
    A = sorted(A)
    B = [A[0]]
    for i in range(1, N):
        B.append(B[-1] - A[i])
    for i in range(N - 2):
        print((B[i], A[i + 1]))
    print((A[N - 1], B[N - 2]))
elif all([a < 0 for a in A]):
    print((S + 2 * max(A)))
    A = sorted(A)
    B = [A[-1]]
    for i in range(N - 1):
        B.append(B[-1] - A[i])
    for i in range(N - 1):
        print((B[i], A[i]))
else:
    print(S)
    A = sorted(A)
    B = [A[0]]
    for i in range(N):
        if N - 1 - 2 - i < 0 or A[-2 - i] < 0:
            print((A[-1 - i], B[-1]))
            B.append(A[-1 - i] - B[-1])
            break
        print((B[-1], A[-1 - i]))
        B.append(B[-1] - A[-1 - i])
    C = [B[-1]]
    for i in range(1, N):
        if A[i] >= 0:
            break
        print((C[-1], A[i]))
        C.append(C[-1] - A[i])


Input:
from collections import deque

def bfs(S,W,H):

    dx=(-1,0,1,0)

    dy=(0,1,0,-1)

    queue=deque([[0,0]])

    visited=[]

    goal=False

    cnt=deque([0])

    while queue and goal==False:

        exe=queue.popleft()

        C=cnt.popleft()

        for i in range(len(dx)):

            x=exe[0]+dx[i]

            y=exe[1]+dy[i]

            if [x,y]==[W-1,H-1]:

                goal=True

            elif 0<=x<=W-1 and 0<=y<=H-1 and S[y][x]==".":

                if [x,y] not in visited:

                    queue.append([x,y])

                    visited.append([x,y])

                    cnt.append(C+1)

    return goal,C+1

def main():

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

    S=[list(eval(input())) for _ in range(H)]

    # number of dot

    num_sharp=0

    for i in range(H):

        for j in range(W):

            if S[i][j]=="#":

                num_sharp+=1

    goal,num=bfs(S,W,H)

    if goal:

        return W*H-num_sharp-(num+1)

    else:

        return -1

if __name__=="__main__":

    print((main()))

from collections import deque

def n_bfs(S,W,H):

    dx=(-1,0,1,0)

    dy=(0,1,0,-1)

    queue=deque([[0,0]])

    d=[[0]*W for _ in range(H)]

    d[0][0]=1

    while queue:

        x,y=queue.popleft()

        for n in range(4):

            nx,ny=x+dx[n],y+dy[n]

            if 0<=nx<=W-1 and 0<=ny<=H-1 and S[ny][nx]=="." and d[ny][nx]==0:

                queue.append([nx,ny])

                d[ny][nx]=d[y][x]+1

    return d[-1][-1]

def n_main():

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

    S=[list(eval(input())) for _ in range(H)]

    ans=n_bfs(S,W,H)

    num_dot=sum(s.count(".") for s in S)

    return num_dot-ans if ans!=0 else -1

if __name__=="__main__":

    print((n_main()))

from collections import deque

def bfs(S, W, H):
    dx = (-1, 0, 1, 0)
    dy = (0, 1, 0, -1)
    queue = deque([[0, 0]])
    visited = []
    goal = False
    cnt = deque([0])
    while queue and goal == False:
        exe = queue.popleft()
        C = cnt.popleft()
        for i in range(len(dx)):
            x = exe[0] + dx[i]
            y = exe[1] + dy[i]
            if [x, y] == [W - 1, H - 1]:
                goal = True
            elif 0 <= x <= W - 1 and 0 <= y <= H - 1 and S[y][x] == ".":
                if [x, y] not in visited:
                    queue.append([x, y])
                    visited.append([x, y])
                    cnt.append(C + 1)
    return goal, C + 1

def main():
    H, W = list(map(int, input().strip().split()))
    S = [list(eval(input())) for _ in range(H)]
    # number of dot
    num_sharp = 0
    for i in range(H):
        for j in range(W):
            if S[i][j] == "#":
                num_sharp += 1
    goal, num = bfs(S, W, H)
    if goal:
        return W * H - num_sharp - (num + 1)
    else:
        return -1

if __name__ == "__main__":
    print((main()))

from collections import deque

def n_bfs(S, W, H):
    dx = (-1, 0, 1, 0)
    dy = (0, 1, 0, -1)
    queue = deque([[0, 0]])
    d = [[0] * W for _ in range(H)]
    d[0][0] = 1
    while queue:
        x, y = queue.popleft()
        for n in range(4):
            nx, ny = x + dx[n], y + dy[n]
            if (
                0 <= nx <= W - 1
                and 0 <= ny <= H - 1
                and S[ny][nx] == "."
                and d[ny][nx] == 0
            ):
                queue.append([nx, ny])
                d[ny][nx] = d[y][x] + 1
    return d[-1][-1]

def n_main():
    H, W = list(map(int, input().strip().split()))
    S = [list(eval(input())) for _ in range(H)]
    ans = n_bfs(S, W, H)
    num_dot = sum(s.count(".") for s in S)
    return num_dot - ans if ans != 0 else -1

if __name__ == "__main__":
    print((n_main()))

-                if [x, y] not in visited:

-                    queue.append([x, y])

-                    visited.append([x, y])

+            nx, ny = x + dx[n], y + dy[n]

-        return W * H - num_sharp - (num + 1)

+    num_dot = sum(s.count(".") for s in S)

+    return num_dot - ans if ans != 0 else -1


Input:
import sys

input = sys.stdin.buffer.readline

n = int(eval(input()))

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

q = int(eval(input()))

from collections import Counter

C = Counter(A)

C = dict(C)

S = sum(A)

for i in range(q):

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

    if b in C:

        vb = C[b]

        C[b] = 0

        S -= b*vb

        S += c*vb

        print(S)

        if c in C:

            C[c] += vb

        else:

            C[c] = vb

    else:

        print(S)

import sys

input = sys.stdin.buffer.readline

n = int(eval(input()))

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

S = sum(A)

D = [0]*(10**5+1)

for a in A:

    D[a] += 1

q = int(eval(input()))

for i in range(q):

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

    S -= D[b]*b

    S += D[b]*c

    D[c] += D[b]

    D[b] = 0

    print(S)

import sys

input = sys.stdin.buffer.readline
n = int(eval(input()))
A = list(map(int, input().split()))
q = int(eval(input()))
from collections import Counter

C = Counter(A)
C = dict(C)
S = sum(A)
for i in range(q):
    b, c = list(map(int, input().split()))
    if b in C:
        vb = C[b]
        C[b] = 0
        S -= b * vb
        S += c * vb
        print(S)
        if c in C:
            C[c] += vb
        else:
            C[c] = vb
    else:
        print(S)

import sys

input = sys.stdin.buffer.readline
n = int(eval(input()))
A = list(map(int, input().split()))
S = sum(A)
D = [0] * (10**5 + 1)
for a in A:
    D[a] += 1
q = int(eval(input()))
for i in range(q):
    b, c = list(map(int, input().split()))
    S -= D[b] * b
    S += D[b] * c
    D[c] += D[b]
    D[b] = 0
    print(S)

+S = sum(A)
+D = [0] * (10**5 + 1)
+for a in A:
+    D[a] += 1
-from collections import Counter
-C = Counter(A)
-C = dict(C)
-S = sum(A)
-    if b in C:
-        vb = C[b]
-        C[b] = 0
-        S -= b * vb
-        S += c * vb
-        print(S)
-        if c in C:
-            C[c] += vb
-        else:
-            C[c] = vb
-    else:
-        print(S)
+    S -= D[b] * b
+    S += D[b] * c
+    D[c] += D[b]
+    D[b] = 0
+    print(S)


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

import sys

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

# 再帰呼び出しの回数制限(デフォルト1000)

sys.setrecursionlimit(10 ** 9)

N = int(eval(input()))

nodes = [[] for _ in range(N+1)]

for i in range(N-1):

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

    # nodes[出発ノード](到着ノード, コスト))

    nodes[a].append((b, c))

    # 無向グラフなのでこっちも入れる

    nodes[b].append((a, c))

memo = [0] * (N+1)

def dfs(cur, prev, dist):

    memo[cur] = dist

    for nxt, cost in nodes[cur]:

        if nxt == prev:

            continue

        dfs(nxt, cur, dist+cost)

Q, K = list(map(int, input().split()))

dfs(K, -1, 0)

for i in range(Q):

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

    # 今回は全てKを経由するので、Kからの距離さえ分かれば全部出る

    print((memo[x] + memo[y]))

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

import sys

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

def list2d(a, b, c): return [[c] * b for i in range(a)]

def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1): return int(-(-x // y))

def INT(): return int(eval(input()))

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

def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes(): print('Yes')

def No(): print('No')

def YES(): print('YES')

def NO(): print('NO')

sys.setrecursionlimit(10 ** 9)

INF = 10 ** 18

MOD = 10 ** 9 + 7

def dijkstra(N: int, nodes: list, src: int) -> list:

    """ ダイクストラ高速化版(頂点数, 隣接リスト(0-indexed), 始点) """

    from heapq import heappush, heappop

    # 頂点[ある始点からの最短距離]

    res = [INF] * N

    # スタート位置

    que = [src]

    res[src] = 0

    # キューが空になるまで

    while len(que) != 0:

        # 距離*N + 現在のノード

        cur = heappop(que)

        # 距離とノードに分ける

        dist = cur // N

        cur %= N

        # 出発ノードcurの到着ノードでループ

        for nxt, cost in nodes[cur]:

            # 今回の経路のが短い時

            if dist + cost < res[nxt]:

                res[nxt] = dist + cost

                # 距離*N+ノード番号 の形でキューに詰める

                heappush(que, (dist+cost)*N+nxt)

    # ノードsrcからの最短距離リストを返却

    return res

N = INT()

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

for i in range(N-1):

    a, b, c = MAP()

    a -= 1; b -= 1

    nodes[a].append((b, c))

    nodes[b].append((a, c))

Q, K = MAP()

K -= 1

res = dijkstra(N, nodes, K)

for i in range(Q):

    x, y = MAP()

    x -= 1; y -= 1

    ans = res[x] + res[y]

    print(ans)

# -*- coding: utf-8 -*-
import sys

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

# 再帰呼び出しの回数制限(デフォルト1000)
sys.setrecursionlimit(10**9)
N = int(eval(input()))
nodes = [[] for _ in range(N + 1)]
for i in range(N - 1):
    a, b, c = list(map(int, input().split()))
    # nodes[出発ノード](到着ノード, コスト))
    nodes[a].append((b, c))
    # 無向グラフなのでこっちも入れる
    nodes[b].append((a, c))
memo = [0] * (N + 1)

def dfs(cur, prev, dist):
    memo[cur] = dist
    for nxt, cost in nodes[cur]:
        if nxt == prev:
            continue
        dfs(nxt, cur, dist + cost)

Q, K = list(map(int, input().split()))
dfs(K, -1, 0)
for i in range(Q):
    x, y = list(map(int, input().split()))
    # 今回は全てKを経由するので、Kからの距離さえ分かれば全部出る
    print((memo[x] + memo[y]))

# -*- coding: utf-8 -*-
import sys

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

def list2d(a, b, c):
    return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
    return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
    return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
    return int(-(-x // y))

def INT():
    return int(eval(input()))

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

def LIST(N=None):
    return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
    print("Yes")

def No():
    print("No")

def YES():
    print("YES")

def NO():
    print("NO")

sys.setrecursionlimit(10**9)
INF = 10**18
MOD = 10**9 + 7

def dijkstra(N: int, nodes: list, src: int) -> list:
    """ダイクストラ高速化版(頂点数, 隣接リスト(0-indexed), 始点)"""
    from heapq import heappush, heappop

    # 頂点[ある始点からの最短距離]
    res = [INF] * N
    # スタート位置
    que = [src]
    res[src] = 0
    # キューが空になるまで
    while len(que) != 0:
        # 距離*N + 現在のノード
        cur = heappop(que)
        # 距離とノードに分ける
        dist = cur // N
        cur %= N
        # 出発ノードcurの到着ノードでループ
        for nxt, cost in nodes[cur]:
            # 今回の経路のが短い時
            if dist + cost < res[nxt]:
                res[nxt] = dist + cost
                # 距離*N+ノード番号 の形でキューに詰める
                heappush(que, (dist + cost) * N + nxt)
    # ノードsrcからの最短距離リストを返却
    return res

N = INT()
nodes = [[] for i in range(N)]
for i in range(N - 1):
    a, b, c = MAP()
    a -= 1
    b -= 1
    nodes[a].append((b, c))
    nodes[b].append((a, c))
Q, K = MAP()
K -= 1
res = dijkstra(N, nodes, K)
for i in range(Q):
    x, y = MAP()
    x -= 1
    y -= 1
    ans = res[x] + res[y]
    print(ans)

-# 再帰呼び出しの回数制限(デフォルト1000)

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

-    # nodes[出発ノード](到着ノード, コスト))

-    # 無向グラフなのでこっちも入れる

+    return [[[d] * c for j in range(b)] for i in range(a)]

+    return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

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

+    return list(MAP()) if N is None else [INT() for i in range(N)]

+def dijkstra(N: int, nodes: list, src: int) -> list:

+    """ダイクストラ高速化版(頂点数, 隣接リスト(0-indexed), 始点)"""

+    from heapq import heappush, heappop

+    # 頂点[ある始点からの最短距離]

+    # スタート位置

+    # キューが空になるまで

+        # 距離*N + 現在のノード

+        # 距離とノードに分ける

+        # 出発ノードcurの到着ノードでループ

+            # 今回の経路のが短い時

+                # 距離*N+ノード番号 の形でキューに詰める

+                heappush(que, (dist + cost) * N + nxt)

+    # ノードsrcからの最短距離リストを返却

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

-    # 今回は全てKを経由するので、Kからの距離さえ分かれば全部出る


Input:
c = [list(map(int, input().split())) for i in range(3) ]

ans = False

for i in range(101) :

    for j in range(101) :

        for k in range(101) :

            b1 = c[0][0] - i

            b2 = c[1][0] - i

            b3 = c[2][0] - i

            if j + b1 != c[0][1] :

                continue

            elif j + b2 != c[1][1] :

                continue

            elif j + b3 != c[2][1] :

                continue

            elif k + b1 != c[0][2] :

                continue

            elif k + b2 != c[1][2] :

                continue

            elif k + b3 != c[2][2] :

                continue

            ans = True

if ans :

    print('Yes')

else :

    print('No')

c = [list(map(int, input().split())) for i in range(3) ]

ans = False

for i in range(101) :

    a1 = 0

    b1 = c[0][0]

    b2 = c[0][1]

    b3 = c[0][2]

    a2 = c[1][0] - b1

    a3 = c[2][0] - b1

    a = []

    a.append(a1)

    a.append(a2)

    a.append(a3)

    if a2 + b2 != c[1][1] :

        continue

    elif a3 + b2 != c[2][1] :

        continue

    elif a2 + b3 != c[1][2] :

        continue

    elif a3 + b3 != c[2][2] :

        continue

    ans = True

    break

if ans :

    print('Yes')

else :

    print('No')

c = [list(map(int, input().split())) for i in range(3)]
ans = False
for i in range(101):
    for j in range(101):
        for k in range(101):
            b1 = c[0][0] - i
            b2 = c[1][0] - i
            b3 = c[2][0] - i
            if j + b1 != c[0][1]:
                continue
            elif j + b2 != c[1][1]:
                continue
            elif j + b3 != c[2][1]:
                continue
            elif k + b1 != c[0][2]:
                continue
            elif k + b2 != c[1][2]:
                continue
            elif k + b3 != c[2][2]:
                continue
            ans = True
if ans:
    print("Yes")
else:
    print("No")

c = [list(map(int, input().split())) for i in range(3)]
ans = False
for i in range(101):
    a1 = 0
    b1 = c[0][0]
    b2 = c[0][1]
    b3 = c[0][2]
    a2 = c[1][0] - b1
    a3 = c[2][0] - b1
    a = []
    a.append(a1)
    a.append(a2)
    a.append(a3)
    if a2 + b2 != c[1][1]:
        continue
    elif a3 + b2 != c[2][1]:
        continue
    elif a2 + b3 != c[1][2]:
        continue
    elif a3 + b3 != c[2][2]:
        continue
    ans = True
    break
if ans:
    print("Yes")
else:
    print("No")


Input:
S = eval(input())

words = ['dream','dreamer','erase','eraser']

damm = True

T = ''

while damm:

    damm = False

    for test in words:

        if S.endswith(test+T):

            T = test + T

            damm = True

            break

    if S == T:

        damm = True

        break

if damm:

    print('YES')

else:

    print('NO')

# import numpy as np

# import math

# import copy

# from collections import deque

import sys

input = sys.stdin.readline

# sys.setrecursionlimit(10000)

def main():

    S = input().rstrip()

    words = ['dream','dreamer','erase','eraser']

    res = 'YES'

    pre = S

    now = S

    while True:

        for i in range(4):

            word = words[i]

            N = len(word)

            M = len(now)

            if N <= M:

                r = now[M-N:]

                if r == word:

                    now = now[:M-N]

        if now == '':

            break

        elif now == pre:

            res = 'NO'

            break

        else:

            pre = now

    print(res)

main()

S = eval(input())
words = ["dream", "dreamer", "erase", "eraser"]
damm = True
T = ""
while damm:
    damm = False
    for test in words:
        if S.endswith(test + T):
            T = test + T
            damm = True
            break
    if S == T:
        damm = True
        break
if damm:
    print("YES")
else:
    print("NO")

# import numpy as np
# import math
# import copy
# from collections import deque
import sys

input = sys.stdin.readline
# sys.setrecursionlimit(10000)
def main():
    S = input().rstrip()
    words = ["dream", "dreamer", "erase", "eraser"]
    res = "YES"
    pre = S
    now = S
    while True:
        for i in range(4):
            word = words[i]
            N = len(word)
            M = len(now)
            if N <= M:
                r = now[M - N :]
                if r == word:
                    now = now[: M - N]
        if now == "":
            break
        elif now == pre:
            res = "NO"
            break
        else:
            pre = now
    print(res)

main()

-words = ["dream", "dreamer", "erase", "eraser"]

+    words = ["dream", "dreamer", "erase", "eraser"]


Input:
b,s=-1e10,1e10

for _ in range(int(eval(input()))):

 r=int(eval(input()))

 b,s=max(b,r-s),min(s,r)

print(b)

import sys

b,s=-1e10,1e10

eval(input())

for r in map(int, sys.stdin.readlines()):

 b,s=max(b,r-s),min(s,r)

print(b)

b, s = -1e10, 1e10
for _ in range(int(eval(input()))):
    r = int(eval(input()))
    b, s = max(b, r - s), min(s, r)
print(b)

import sys

b, s = -1e10, 1e10
eval(input())
for r in map(int, sys.stdin.readlines()):
    b, s = max(b, r - s), min(s, r)
print(b)

+for r in map(int, sys.stdin.readlines()):


Input:
import fractions

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

b//=fractions.gcd(a,b)

a,c=2,1

while a**2<=b:

    if b%a==0:

        c*=a

        while b%a==0: b//=a

    a+=1

print((c*b))

def gcd(a, b):

    while b: a, b = b, a % b

    return a

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

b//=gcd(a,b)

a,c=2,1

while a*a<=b:

    if b%a==0:

        c*=a

        while b%a==0:b//=a

    a+=1

print(([c*b,c][b==1]))

import fractions

a, b = list(map(int, input().split()))
b //= fractions.gcd(a, b)
a, c = 2, 1
while a**2 <= b:
    if b % a == 0:
        c *= a
        while b % a == 0:
            b //= a
    a += 1
print((c * b))

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

a, b = list(map(int, input().split()))
b //= gcd(a, b)
a, c = 2, 1
while a * a <= b:
    if b % a == 0:
        c *= a
        while b % a == 0:
            b //= a
    a += 1
print(([c * b, c][b == 1]))

-import fractions
+def gcd(a, b):
+    while b:
+        a, b = b, a % b
+    return a
+
-b //= fractions.gcd(a, b)
+b //= gcd(a, b)
-while a**2 <= b:
+while a * a <= b:
-print((c * b))
+print(([c * b, c][b == 1]))


Input:
import itertools

import math

import fractions

import functools

import copy

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

pyi = []

for i in range(m):

    p,y= list(map(int, input().split()))

    pyi.append([p,y,i])

pyi.sort(key=lambda x: x[1])

pyi.sort(key=lambda x: x[0])

ken = 0

for i in range(m):

    if pyi[i][0] != ken:

        ken = pyi[i][0]

        x = 1

    else:

        x += 1

    pyi[i].append(x)

pyi.sort(key=lambda x: x[2])

for i in range(m):

    print((str(pyi[i][0]).zfill(6)+str(pyi[i][3]).zfill(6)))

def main():

    # n = int(input())

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

    # v = list(map(int, input().split()))

    # s = input()

    py = []

    for i in range(m):

        p, y = list(map(int, input().split()))

        py.append([i, p, y])

    py.sort(key=lambda x: (x[1], x[2]))

    num = 1

    for i in range(0, m):

        if i == 0:

            py[i].append(num)

        else:

            if py[i][1] == py[i-1][1]:

                num += 1

            else:

                num = 1

            py[i].append(num)

    py.sort(key=lambda x: x[0])

    for i in range(m):

        print((str(py[i][1]).zfill(6) + str(py[i][3]).zfill(6)))

if __name__ == '__main__':

    main()

import itertools
import math
import fractions
import functools
import copy

n, m = list(map(int, input().split()))
pyi = []
for i in range(m):
    p, y = list(map(int, input().split()))
    pyi.append([p, y, i])
pyi.sort(key=lambda x: x[1])
pyi.sort(key=lambda x: x[0])
ken = 0
for i in range(m):
    if pyi[i][0] != ken:
        ken = pyi[i][0]
        x = 1
    else:
        x += 1
    pyi[i].append(x)
pyi.sort(key=lambda x: x[2])
for i in range(m):
    print((str(pyi[i][0]).zfill(6) + str(pyi[i][3]).zfill(6)))

def main():
    # n = int(input())
    n, m = list(map(int, input().split()))
    # v = list(map(int, input().split()))
    # s = input()
    py = []
    for i in range(m):
        p, y = list(map(int, input().split()))
        py.append([i, p, y])
    py.sort(key=lambda x: (x[1], x[2]))
    num = 1
    for i in range(0, m):
        if i == 0:
            py[i].append(num)
        else:
            if py[i][1] == py[i - 1][1]:
                num += 1
            else:
                num = 1
            py[i].append(num)
    py.sort(key=lambda x: x[0])
    for i in range(m):
        print((str(py[i][1]).zfill(6) + str(py[i][3]).zfill(6)))

if __name__ == "__main__":
    main()

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

+    # v = list(map(int, input().split()))

+        p, y = list(map(int, input().split()))

+    py.sort(key=lambda x: (x[1], x[2]))

-    p, y = list(map(int, input().split()))

-    print((str(pyi[i][0]).zfill(6) + str(pyi[i][3]).zfill(6)))


Input:
import sys

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

sys.setrecursionlimit(max(1000, 10**9))

write = lambda x: sys.stdout.write(x+"\n")

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

from collections import defaultdict

ns0 = defaultdict(list)

ns1 = defaultdict(list)

for i in range(k):

    p,q = list(map(int, input().split()))

    p-=1;q-=1

    ns0[p].append(q)

    ns0[q].append(p)

for i in range(l):

    p,q = list(map(int, input().split()))

    p-=1;q-=1

    ns1[p].append(q)

    ns1[q].append(p)

def sub(ns):

    seen = [None]*n

    num = 1

    for i in range(n):

        if seen[i] is not None:

            continue

        q = [i]

        seen[i] = num

        while q:

            u = q.pop()

            for v in ns[u]:

                if seen[v] is not None:

                    continue

                seen[v] = num

                q.append(v)

        num += 1

    return seen

s1 = sub(ns0)

s2 = sub(ns1)

import gc

del ns0, ns1

gc.collect()

d1 = [None]*(max(s1)+1)

d2 = [None]*(max(s2)+1)

def update(d,ind,i):

    if d[ind] is None:

        d[ind] = set([i])

    else:

        d[ind].add(i)

for i in range(n):

    update(d1,s1[i],i)

    update(d2,s2[i],i)

#     d1[s1[i]].add(i)

#     d2[s2[i]].add(i)

d = {}

ans = [None]*n

for i in range(n):

    u,v = s1.pop(), s2.pop()

    if (u,v) not in d:

        d[u,v] = len(d1[u] & d2[v])

    ans[-(i+1)] = d[u,v]

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

import sys

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

sys.setrecursionlimit(max(1000, 10**9))

write = lambda x: sys.stdout.write(x+"\n")

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

from collections import defaultdict

ns0 = defaultdict(list)

ns1 = defaultdict(list)

for i in range(k):

    p,q = list(map(int, input().split()))

    p-=1;q-=1

    ns0[p].append(q)

    ns0[q].append(p)

for i in range(l):

    p,q = list(map(int, input().split()))

    p-=1;q-=1

    ns1[p].append(q)

    ns1[q].append(p)

def sub(ns):

    seen = [None]*n

    num = 1

    for i in range(n):

        if seen[i] is not None:

            continue

        q = [i]

        seen[i] = num

        while q:

            u = q.pop()

            for v in ns[u]:

                if seen[v] is not None:

                    continue

                seen[v] = num

                q.append(v)

        num += 1

    return seen

s1 = sub(ns0)

s2 = sub(ns1)

import gc

del ns0, ns1

gc.collect()

from collections import Counter

c = Counter([(s1[i], s2[i]) for i in range(n)])

ans = [(c[s1[i],s2[i]]) for i in range(n)]

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

import sys

input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x + "\n")
n, k, l = list(map(int, input().split()))
from collections import defaultdict

ns0 = defaultdict(list)
ns1 = defaultdict(list)
for i in range(k):
    p, q = list(map(int, input().split()))
    p -= 1
    q -= 1
    ns0[p].append(q)
    ns0[q].append(p)
for i in range(l):
    p, q = list(map(int, input().split()))
    p -= 1
    q -= 1
    ns1[p].append(q)
    ns1[q].append(p)

def sub(ns):
    seen = [None] * n
    num = 1
    for i in range(n):
        if seen[i] is not None:
            continue
        q = [i]
        seen[i] = num
        while q:
            u = q.pop()
            for v in ns[u]:
                if seen[v] is not None:
                    continue
                seen[v] = num
                q.append(v)
        num += 1
    return seen

s1 = sub(ns0)
s2 = sub(ns1)
import gc

del ns0, ns1
gc.collect()
d1 = [None] * (max(s1) + 1)
d2 = [None] * (max(s2) + 1)

def update(d, ind, i):
    if d[ind] is None:
        d[ind] = set([i])
    else:
        d[ind].add(i)

for i in range(n):
    update(d1, s1[i], i)
    update(d2, s2[i], i)
#     d1[s1[i]].add(i)
#     d2[s2[i]].add(i)
d = {}
ans = [None] * n
for i in range(n):
    u, v = s1.pop(), s2.pop()
    if (u, v) not in d:
        d[u, v] = len(d1[u] & d2[v])
    ans[-(i + 1)] = d[u, v]
write(" ".join(map(str, ans)))

import sys

input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x + "\n")
n, k, l = list(map(int, input().split()))
from collections import defaultdict

ns0 = defaultdict(list)
ns1 = defaultdict(list)
for i in range(k):
    p, q = list(map(int, input().split()))
    p -= 1
    q -= 1
    ns0[p].append(q)
    ns0[q].append(p)
for i in range(l):
    p, q = list(map(int, input().split()))
    p -= 1
    q -= 1
    ns1[p].append(q)
    ns1[q].append(p)

def sub(ns):
    seen = [None] * n
    num = 1
    for i in range(n):
        if seen[i] is not None:
            continue
        q = [i]
        seen[i] = num
        while q:
            u = q.pop()
            for v in ns[u]:
                if seen[v] is not None:
                    continue
                seen[v] = num
                q.append(v)
        num += 1
    return seen

s1 = sub(ns0)
s2 = sub(ns1)
import gc

del ns0, ns1
gc.collect()
from collections import Counter

c = Counter([(s1[i], s2[i]) for i in range(n)])
ans = [(c[s1[i], s2[i]]) for i in range(n)]
write(" ".join(map(str, ans)))

+c = Counter([(s1[i], s2[i]) for i in range(n)])

+ans = [(c[s1[i], s2[i]]) for i in range(n)]


Input:
from heapq import*

import sys

input=sys.stdin.readline

def DIJKSTRA(point,d):

    cost      = [1e18]*(n+1)

    Q         = []  #頂点のリスト

    cost[point]=0  #開始地点のコストをゼロとする（当たり前

    heappush(Q,(point,cost[point]))

    while Q:

        prefnd,tmpC=heappop(Q)

        if cost[prefnd]<tmpC:

            continue

        for node,c in d[prefnd]:

            altC=c+tmpC

            if cost[node]>altC:

                cost[node]=altC

                heappush(Q,(node,altC))

    return cost

n=int(eval(input()))

d=[[]for i in range(n+1)]

for i in range(n-1):

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

    d[a].append([b,c])

    d[b].append([a,c])

q,k=list(map(int,input().split()))

y=DIJKSTRA(k,d)

for i in range(q):

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

    print((y[a]+y[b]))

from collections import*

from heapq import*

import sys

input=sys.stdin.readline

def BFS(point,d):

    cost=[1e18]*(n+1)

    cost[point]=0

    Q=deque()

    Q.appendleft((0,point))

    while Q:

        c,p=Q.pop()

        for np,co in d[p]:

            if cost[np]==1e18:

                cost[np]=c+co

                Q.appendleft((c+co,np))

    return cost

n=int(eval(input()))

d=[[]for i in range(n+1)]

for i in range(n-1):

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

    d[a].append([b,c])

    d[b].append([a,c])

#print(d)

q,k=list(map(int,input().split()))

y=BFS(k,d)

for i in range(q):

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

    print((y[a]+y[b]))

from heapq import *
import sys

input = sys.stdin.readline

def DIJKSTRA(point, d):
    cost = [1e18] * (n + 1)
    Q = []  # 頂点のリスト
    cost[point] = 0  # 開始地点のコストをゼロとする（当たり前
    heappush(Q, (point, cost[point]))
    while Q:
        prefnd, tmpC = heappop(Q)
        if cost[prefnd] < tmpC:
            continue
        for node, c in d[prefnd]:
            altC = c + tmpC
            if cost[node] > altC:
                cost[node] = altC
                heappush(Q, (node, altC))
    return cost

n = int(eval(input()))
d = [[] for i in range(n + 1)]
for i in range(n - 1):
    a, b, c = list(map(int, input().split()))
    d[a].append([b, c])
    d[b].append([a, c])
q, k = list(map(int, input().split()))
y = DIJKSTRA(k, d)
for i in range(q):
    a, b = list(map(int, input().split()))
    print((y[a] + y[b]))

from collections import *
from heapq import *
import sys

input = sys.stdin.readline

def BFS(point, d):
    cost = [1e18] * (n + 1)
    cost[point] = 0
    Q = deque()
    Q.appendleft((0, point))
    while Q:
        c, p = Q.pop()
        for np, co in d[p]:
            if cost[np] == 1e18:
                cost[np] = c + co
                Q.appendleft((c + co, np))
    return cost

n = int(eval(input()))
d = [[] for i in range(n + 1)]
for i in range(n - 1):
    a, b, c = list(map(int, input().split()))
    d[a].append([b, c])
    d[b].append([a, c])
# print(d)
q, k = list(map(int, input().split()))
y = BFS(k, d)
for i in range(q):
    a, b = list(map(int, input().split()))
    print((y[a] + y[b]))

-    Q = []  # 頂点のリスト

-    cost[point] = 0  # 開始地点のコストをゼロとする（当たり前

-                heappush(Q, (node, altC))

+                Q.appendleft((c + co, np))


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, gcd

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 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 TUPLE(): return tuple(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

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

N = INT()

A = [INT() for _ in range(N)]

tmp = 0

cnt = 0

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

	tmp -= 1

	if i < A[i]:

		print((-1))

		exit()

	elif A[i] < tmp:

		print((-1))

		exit()

	elif tmp < A[i]:

		cnt += A[i]

		tmp = A[i]

print(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, gcd

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 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 TUPLE(): return tuple(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

#mod = 998244353

from decimal import *

#import numpy as np

#decimal.getcontext().prec = 10

N = INT()

A = [INT() for _ in range(N)]

ans = 0

tmp = A[0]

for i, a in enumerate(A):

	if i < a or tmp+1 < a:

		print((-1))

		break

	if a != tmp+1:

		ans += tmp

	tmp = a

else:

	ans += tmp

	print(ans)

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,
    gcd,
)
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 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 TUPLE():
    return tuple(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
# mod = 998244353
from decimal import *

# import numpy as np
# decimal.getcontext().prec = 10
N = INT()
A = [INT() for _ in range(N)]
tmp = 0
cnt = 0
for i in range(N - 1, -1, -1):
    tmp -= 1
    if i < A[i]:
        print((-1))
        exit()
    elif A[i] < tmp:
        print((-1))
        exit()
    elif tmp < A[i]:
        cnt += A[i]
        tmp = A[i]
print(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,
    gcd,
)
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 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 TUPLE():
    return tuple(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
# mod = 998244353
from decimal import *

# import numpy as np
# decimal.getcontext().prec = 10
N = INT()
A = [INT() for _ in range(N)]
ans = 0
tmp = A[0]
for i, a in enumerate(A):
    if i < a or tmp + 1 < a:
        print((-1))
        break
    if a != tmp + 1:
        ans += tmp
    tmp = a
else:
    ans += tmp
    print(ans)

-tmp = 0
-cnt = 0
-for i in range(N - 1, -1, -1):
-    tmp -= 1
-    if i < A[i]:
+ans = 0
+tmp = A[0]
+for i, a in enumerate(A):
+    if i < a or tmp + 1 < a:
-        exit()
-    elif A[i] < tmp:
-        print((-1))
-        exit()
-    elif tmp < A[i]:
-        cnt += A[i]
-        tmp = A[i]
-print(cnt)
+        break
+    if a != tmp + 1:
+        ans += tmp
+    tmp = a
+else:
+    ans += tmp
+    print(ans)


Input:
import math

# inputList=[]

# for i in range(6):

#     inputNum = input()

#     inputList.append(inputNum)

inputa = input().split()

# inputb = input().split()

a = int(inputa[0])

b = int(inputa[1])

c = int(inputa[2])

# x = int(inputb[0])

# y = int(inputb[1])

ans = int(math.floor(float(b)/float(a)))

if ans > c:

    ans = c

print(ans)

import sys

import re

import math

# import bisect

# import copy

# import heapq

# from collections import deque

# import decimal

# sys.setrecursionlimit(100001)

INF = sys.maxsize

# MOD = 10 ** 9 + 7

ni = lambda: int(sys.stdin.readline())

ns = lambda: list(map(int, sys.stdin.readline().split()))

na = lambda: list(map(int, sys.stdin.readline().split()))

# ===CODE===

def main():

    a,b,c=ns()

    print((min(c, b//a)))

if __name__ == '__main__':

    main()

import math

# inputList=[]
# for i in range(6):
#     inputNum = input()
#     inputList.append(inputNum)
inputa = input().split()
# inputb = input().split()
a = int(inputa[0])
b = int(inputa[1])
c = int(inputa[2])
# x = int(inputb[0])
# y = int(inputb[1])
ans = int(math.floor(float(b) / float(a)))
if ans > c:
    ans = c
print(ans)

import sys
import re
import math

# import bisect
# import copy
# import heapq
# from collections import deque
# import decimal
# sys.setrecursionlimit(100001)
INF = sys.maxsize
# MOD = 10 ** 9 + 7
ni = lambda: int(sys.stdin.readline())
ns = lambda: list(map(int, sys.stdin.readline().split()))
na = lambda: list(map(int, sys.stdin.readline().split()))
# ===CODE===
def main():
    a, b, c = ns()
    print((min(c, b // a)))

if __name__ == "__main__":
    main()

-ans = int(math.floor(float(b) / float(a)))

+ns = lambda: list(map(int, sys.stdin.readline().split()))

+na = lambda: list(map(int, sys.stdin.readline().split()))


Input:
from sys import stdin

import math

import fractions

from collections import deque

from collections import Counter

import itertools

INF = 10 ** 10

# N個の部屋とM本の通路

N, M = [int(x) for x in stdin.readline().rstrip().split()]

route = [[] for _ in range(N+1)]

for _ in range(M):

    A, B = [int(x) for x in stdin.readline().rstrip().split()]

    route[A].append(B)

    route[B].append(A)

kyori_to_1 = [INF for _ in range(N+1)]

kyori_to_1[1] = 0

miti = [0 for _ in range(N+1)]

miti[0] = -1

miti[1] = -1

is_visited = [False for _ in range(N+1)]

# 幅優先探索

# 試すべき位置をキューで管理

que = deque([1])

# キューが空じゃなければ

while len(que) != 0:

    now = que.popleft()

    if is_visited[now]:

        continue

    is_visited[now] = True

    for place in route[now]:

        que.append(place)

        if kyori_to_1[now]+1 < kyori_to_1[place]:

            kyori_to_1[place] = kyori_to_1[now]+1

            miti[place] = now

if 0 in miti:

    print("No")

else:

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

        if i == 1:

            print("Yes")

        else:

            print((miti[i]))

from sys import stdin

import math

import fractions

from collections import deque

from collections import Counter

import itertools

INF = 10 ** 10

# N個の部屋とM本の通路

N, M = [int(x) for x in stdin.readline().rstrip().split()]

route = [[] for _ in range(N+1)]

# A->B と B->A をリストに保存していく

# AとBは "1以上" を想定

for _ in range(M):

    A, B = [int(x) for x in stdin.readline().rstrip().split()]

    route[A].append(B)

    route[B].append(A)

# 場所1までの距離

dist_to_1 = [INF for _ in range(N+1)]

dist_to_1[1] = 0

# next_route[i] = j: 場所iがゴールに最短でたどり着くために向かう場所j

next_route = [0 for _ in range(N+1)]

# 場所iに訪れたかどうか

is_visited = [False for _ in range(N+1)]

# 幅優先探索

# 試すべき位置をキューで管理

que = deque([1])

# キューが空じゃなければ

while len(que) != 0:

    now = que.popleft()

    # 過去に訪れていれば無視

    if is_visited[now]:

        continue

    is_visited[now] = True

    # そこからいける場所を幅優先探索で

    for place in route[now]:

        que.append(place)

        # 距離とルートの更新

        if dist_to_1[now]+1 < dist_to_1[place]:

            dist_to_1[place] = dist_to_1[now]+1

            next_route[place] = now

# 場所2以降において、どこか次の道が見つかってない場合は

# ゴールにいけないということ

if 0 in next_route[2:]:

    print("No")

else:

    print("Yes")

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

        print((next_route[i]))

from sys import stdin
import math
import fractions
from collections import deque
from collections import Counter
import itertools

INF = 10**10
# N個の部屋とM本の通路
N, M = [int(x) for x in stdin.readline().rstrip().split()]
route = [[] for _ in range(N + 1)]
for _ in range(M):
    A, B = [int(x) for x in stdin.readline().rstrip().split()]
    route[A].append(B)
    route[B].append(A)
kyori_to_1 = [INF for _ in range(N + 1)]
kyori_to_1[1] = 0
miti = [0 for _ in range(N + 1)]
miti[0] = -1
miti[1] = -1
is_visited = [False for _ in range(N + 1)]
# 幅優先探索
# 試すべき位置をキューで管理
que = deque([1])
# キューが空じゃなければ
while len(que) != 0:
    now = que.popleft()
    if is_visited[now]:
        continue
    is_visited[now] = True
    for place in route[now]:
        que.append(place)
        if kyori_to_1[now] + 1 < kyori_to_1[place]:
            kyori_to_1[place] = kyori_to_1[now] + 1
            miti[place] = now
if 0 in miti:
    print("No")
else:
    for i in range(1, N + 1):
        if i == 1:
            print("Yes")
        else:
            print((miti[i]))

from sys import stdin
import math
import fractions
from collections import deque
from collections import Counter
import itertools

INF = 10**10
# N個の部屋とM本の通路
N, M = [int(x) for x in stdin.readline().rstrip().split()]
route = [[] for _ in range(N + 1)]
# A->B と B->A をリストに保存していく
# AとBは "1以上" を想定
for _ in range(M):
    A, B = [int(x) for x in stdin.readline().rstrip().split()]
    route[A].append(B)
    route[B].append(A)
# 場所1までの距離
dist_to_1 = [INF for _ in range(N + 1)]
dist_to_1[1] = 0
# next_route[i] = j: 場所iがゴールに最短でたどり着くために向かう場所j
next_route = [0 for _ in range(N + 1)]
# 場所iに訪れたかどうか
is_visited = [False for _ in range(N + 1)]
# 幅優先探索
# 試すべき位置をキューで管理
que = deque([1])
# キューが空じゃなければ
while len(que) != 0:
    now = que.popleft()
    # 過去に訪れていれば無視
    if is_visited[now]:
        continue
    is_visited[now] = True
    # そこからいける場所を幅優先探索で
    for place in route[now]:
        que.append(place)
        # 距離とルートの更新
        if dist_to_1[now] + 1 < dist_to_1[place]:
            dist_to_1[place] = dist_to_1[now] + 1
            next_route[place] = now
# 場所2以降において、どこか次の道が見つかってない場合は
# ゴールにいけないということ
if 0 in next_route[2:]:
    print("No")
else:
    print("Yes")
    for i in range(2, N + 1):
        print((next_route[i]))

+# A->B と B->A をリストに保存していく

+# AとBは "1以上" を想定

-kyori_to_1 = [INF for _ in range(N + 1)]

+dist_to_1 = [INF for _ in range(N + 1)]

+# next_route[i] = j: 場所iがゴールに最短でたどり着くために向かう場所j

+# 場所iに訪れたかどうか

+    # 過去に訪れていれば無視

+    # そこからいける場所を幅優先探索で

-        if kyori_to_1[now] + 1 < kyori_to_1[place]:

-            kyori_to_1[place] = kyori_to_1[now] + 1

+        # 距離とルートの更新

+        if dist_to_1[now] + 1 < dist_to_1[place]:

+            dist_to_1[place] = dist_to_1[now] + 1

+# 場所2以降において、どこか次の道が見つかってない場合は

+# ゴールにいけないということ


Input:
from collections import deque

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

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

A.appendleft(K - A[-1] + A[0])

sa_max = A[0]

for i in range(1, N):

    sa = A[i + 1] - A[i]

    if sa_max < sa:

        sa_max = sa

print((A[-1] + A[0] - (sa_max + A[1])))

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

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

A.append(K - A[-1] + A[0])

sa_max = A[-1]

for i in range(N - 1):

    sa = A[i + 1] - A[i]

    if sa_max < sa:

        sa_max = sa

print(((A[-2] - A[0]) + A[-1] - sa_max))

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


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

left, right = 1, n

for _ in range(m):

  l, r = list(map(int, input().split()))

  if l > left:

    left = l

  if r < right:

    right = r

  if left > right:

    print((0))

    quit()

print((right - left + 1))

import sys

n, m, *lst = list(map(int, sys.stdin.read().split()))

l = max(lst[::2])

r = min(lst[1::2])

if l > r:

  print((0))

else:

  print((r - l + 1))

-    l, r = list(map(int, input().split()))

+n, m, *lst = list(map(int, sys.stdin.read().split()))


Input:
from sys import stdin

def main():

    #入力

    readline=stdin.readline

    n=int(readline())

    ans=0

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

        n_min=i

        n_max=n//i*i

        ans+=(n//i)*(n_min+n_max)//2

    print(ans)

if __name__=="__main__":

    main()

from sys import stdin

import numpy as np

def main():

    #入力

    readline=stdin.readline

    n=int(readline())

    ans=0

    n_min=np.arange(1,n+1,dtype=np.int64)

    n_max=n//n_min*n_min

    kousu=n//n_min

    ans=(kousu*(n_min+n_max)//2).sum()

    print(ans)

if __name__=="__main__":

    main()

from sys import stdin

def main():
    # 入力
    readline = stdin.readline
    n = int(readline())
    ans = 0
    for i in range(1, n + 1):
        n_min = i
        n_max = n // i * i
        ans += (n // i) * (n_min + n_max) // 2
    print(ans)

if __name__ == "__main__":
    main()

from sys import stdin
import numpy as np

def main():
    # 入力
    readline = stdin.readline
    n = int(readline())
    ans = 0
    n_min = np.arange(1, n + 1, dtype=np.int64)
    n_max = n // n_min * n_min
    kousu = n // n_min
    ans = (kousu * (n_min + n_max) // 2).sum()
    print(ans)

if __name__ == "__main__":
    main()

+    n_min = np.arange(1, n + 1, dtype=np.int64)

+    ans = (kousu * (n_min + n_max) // 2).sum()


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

max = -float('inf')

x = []

y = []

z = []

for i in range(N):

	xx,yy,zz = list(map(int,input().split()))

	x.append(xx)

	y.append(yy)

	z.append(zz)

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

	for j in range(-1,2,2):

		for k in range(-1,2,2):

			s = []

			for m in range(N):

				s.append(i*x[m]+j*y[m]+k*z[m])

			s = sorted(s)

			tmp = sum(s[-1*M:])

			if tmp > max:

				max = tmp

if M==0:

	print((0))

else:

	print(max)

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

xyz = [list(map(int,input().split())) for _ in range(n)]

res = 0

for a in (1,-1):

    for b in (1,-1):

        for c in (1,-1):

            l = []

            for (x,y,z) in xyz:

                l.append(x*a+y*b+z*c)

            l = sorted(l,reverse=True)

            res = max(res, sum(l[:m]))

print(res)

N, M = list(map(int, input().split()))
max = -float("inf")
x = []
y = []
z = []
for i in range(N):
    xx, yy, zz = list(map(int, input().split()))
    x.append(xx)
    y.append(yy)
    z.append(zz)
for i in range(-1, 2, 2):
    for j in range(-1, 2, 2):
        for k in range(-1, 2, 2):
            s = []
            for m in range(N):
                s.append(i * x[m] + j * y[m] + k * z[m])
            s = sorted(s)
            tmp = sum(s[-1 * M :])
            if tmp > max:
                max = tmp
if M == 0:
    print((0))
else:
    print(max)

n, m = list(map(int, input().split()))
xyz = [list(map(int, input().split())) for _ in range(n)]
res = 0
for a in (1, -1):
    for b in (1, -1):
        for c in (1, -1):
            l = []
            for (x, y, z) in xyz:
                l.append(x * a + y * b + z * c)
            l = sorted(l, reverse=True)
            res = max(res, sum(l[:m]))
print(res)

-    xx, yy, zz = list(map(int, input().split()))

-                s.append(i * x[m] + j * y[m] + k * z[m])

+xyz = [list(map(int, input().split())) for _ in range(n)]

+                l.append(x * a + y * b + z * c)

+            l = sorted(l, reverse=True)


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

connected = [list(map(int,input().split())) for _ in range(M)]

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

ans = 0

for i in range(1<<N):

    count1 = 0

    for j,lst in enumerate(connected):

        count2 = 0

        for s in lst[1:]:

            if (i>>(s-1)) & 1:

                count2 += 1

        if count2 % 2 == condition[j]:

            count1 += 1

    if count1 == M:

        ans += 1

print(ans)

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

connected = [list(map(int,input().split())) for _ in range(M)]

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

ans = 0

for i in range(1<<N):

    FLG = True

    for j,lst in enumerate(connected):

        count2 = 0

        for s in lst[1:]:

            if (i>>(s-1)) & 1:

                count2 += 1

        if count2 % 2 != condition[j]:

            FLG = False

            break

    if FLG:

        ans += 1

print(ans)

N, M = list(map(int, input().split()))
connected = [list(map(int, input().split())) for _ in range(M)]
condition = list(map(int, input().split()))
ans = 0
for i in range(1 << N):
    count1 = 0
    for j, lst in enumerate(connected):
        count2 = 0
        for s in lst[1:]:
            if (i >> (s - 1)) & 1:
                count2 += 1
        if count2 % 2 == condition[j]:
            count1 += 1
    if count1 == M:
        ans += 1
print(ans)

N, M = list(map(int, input().split()))
connected = [list(map(int, input().split())) for _ in range(M)]
condition = list(map(int, input().split()))
ans = 0
for i in range(1 << N):
    FLG = True
    for j, lst in enumerate(connected):
        count2 = 0
        for s in lst[1:]:
            if (i >> (s - 1)) & 1:
                count2 += 1
        if count2 % 2 != condition[j]:
            FLG = False
            break
    if FLG:
        ans += 1
print(ans)

-    count1 = 0
+    FLG = True
-        if count2 % 2 == condition[j]:
-            count1 += 1
-    if count1 == M:
+        if count2 % 2 != condition[j]:
+            FLG = False
+            break
+    if FLG:


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

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

B = [0]*n

for i in reversed(list(range(n))):

    j = i+1

    cnt = 0

    while j <= n:

        cnt += B[j-1]

        j += i+1

    if cnt%2 != A[i]:

        B[i] = 1

m = 0

ans = []

for i, b in enumerate(B):

    if b != 0:

        m += 1

        ans.append(i+1)

print(m)

if len(ans) > 0:

    print((*ans))

n =int(eval(input()))

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

ans = [0]*n

for i in reversed(list(range(n))):

    j = i+1

    b = 0

    while j <= n:

        b += ans[j-1]

        j += (i+1)

    if b%2 == A[i]:

        ans[i] = 0

    else:

        ans[i] = 1

print((sum(ans)))

B = []

for i in range(len(ans)):

    if ans[i] != 0:

        B.append(i+1)

print((*B))

n = int(eval(input()))
A = list(map(int, input().split()))
B = [0] * n
for i in reversed(list(range(n))):
    j = i + 1
    cnt = 0
    while j <= n:
        cnt += B[j - 1]
        j += i + 1
    if cnt % 2 != A[i]:
        B[i] = 1
m = 0
ans = []
for i, b in enumerate(B):
    if b != 0:
        m += 1
        ans.append(i + 1)
print(m)
if len(ans) > 0:
    print((*ans))

n = int(eval(input()))
A = list(map(int, input().split()))
ans = [0] * n
for i in reversed(list(range(n))):
    j = i + 1
    b = 0
    while j <= n:
        b += ans[j - 1]
        j += i + 1
    if b % 2 == A[i]:
        ans[i] = 0
    else:
        ans[i] = 1
print((sum(ans)))
B = []
for i in range(len(ans)):
    if ans[i] != 0:
        B.append(i + 1)
print((*B))

-B = [0] * n
+ans = [0] * n
-    cnt = 0
+    b = 0
-        cnt += B[j - 1]
+        b += ans[j - 1]
-    if cnt % 2 != A[i]:
-        B[i] = 1
-m = 0
-ans = []
-for i, b in enumerate(B):
-    if b != 0:
-        m += 1
-        ans.append(i + 1)
-print(m)
-if len(ans) > 0:
-    print((*ans))
+    if b % 2 == A[i]:
+        ans[i] = 0
+    else:
+        ans[i] = 1
+print((sum(ans)))
+B = []
+for i in range(len(ans)):
+    if ans[i] != 0:
+        B.append(i + 1)
+print((*B))


Input:
#!/usr/bin/env python3

import sys

MOD = 1000000007  # type: int

def solve(S: str):

    N = len(S)

    # 0:文字列の総数 1:Aの数  2:ABの数 3:ABCの数

    ## dp[i][j] = i文字目まで見たときに状態jの数

    ## answer: dp[N][3]

    dp = [[0]*4 for _ in range(N+1)]

    dp[0][0] = 1

    for i in range(N):

        for j in (0,1,2,3):

            if S[i] == "?":

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

            else:

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

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

        ## カウント進める場合

        if S[i] == "A" or S[i] == "?":

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

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

        if S[i] == "B" or S[i] == "?":

            dp[i+1][2] += dp[i][1]

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

        if S[i] == "C" or S[i] == "?":

            dp[i+1][3] += dp[i][2]

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

    print((dp[N][3]%MOD))

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

    S = next(tokens)  # type: str

    solve(S)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3

import sys

MOD = 1000000007  # type: int

def solve(S: str):

    N = len(S)

    # 0:文字列の総数 1:Aの数  2:ABの数 3:ABCの数

    ## dp[i][j] = i文字目まで見たときに状態jの数

    ## answer: dp[N][3]

    dp = [[0]*4 for _ in range(N+1)]

    dp[0][0] = 1

    for i in range(N):

        for j in (0,1,2,3):

            if S[i] == "?":

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

            else:

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

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

        ## カウント進める場合

        if S[i] == "A" or S[i] == "?":

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

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

        if S[i] == "B" or S[i] == "?":

            dp[i+1][2] += dp[i][1]

            # dp[i+1][2] %= MOD

        if S[i] == "C" or S[i] == "?":

            dp[i+1][3] += dp[i][2]

            # dp[i+1][3] %= MOD

    print((dp[N][3]%MOD))

    return

def main():

    def iterate_tokens():

        for line in sys.stdin:

            for word in line.split():

                yield word

    tokens = iterate_tokens()

    S = next(tokens)  # type: str

    solve(S)

if __name__ == '__main__':

    main()

#!/usr/bin/env python3
import sys

MOD = 1000000007  # type: int

def solve(S: str):
    N = len(S)
    # 0:文字列の総数 1:Aの数  2:ABの数 3:ABCの数
    ## dp[i][j] = i文字目まで見たときに状態jの数
    ## answer: dp[N][3]
    dp = [[0] * 4 for _ in range(N + 1)]
    dp[0][0] = 1
    for i in range(N):
        for j in (0, 1, 2, 3):
            if S[i] == "?":
                dp[i + 1][j] += dp[i][j] * 3
            else:
                dp[i + 1][j] += dp[i][j]
            dp[i + 1][j] %= MOD
        ## カウント進める場合
        if S[i] == "A" or S[i] == "?":
            dp[i + 1][1] += dp[i][0]
            dp[i + 1][1] %= MOD
        if S[i] == "B" or S[i] == "?":
            dp[i + 1][2] += dp[i][1]
            dp[i + 1][2] %= MOD
        if S[i] == "C" or S[i] == "?":
            dp[i + 1][3] += dp[i][2]
            dp[i + 1][3] %= MOD
    print((dp[N][3] % MOD))
    return

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

    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == "__main__":
    main()

#!/usr/bin/env python3
import sys

MOD = 1000000007  # type: int

def solve(S: str):
    N = len(S)
    # 0:文字列の総数 1:Aの数  2:ABの数 3:ABCの数
    ## dp[i][j] = i文字目まで見たときに状態jの数
    ## answer: dp[N][3]
    dp = [[0] * 4 for _ in range(N + 1)]
    dp[0][0] = 1
    for i in range(N):
        for j in (0, 1, 2, 3):
            if S[i] == "?":
                dp[i + 1][j] += dp[i][j] * 3
            else:
                dp[i + 1][j] += dp[i][j]
            dp[i + 1][j] %= MOD
        ## カウント進める場合
        if S[i] == "A" or S[i] == "?":
            dp[i + 1][1] += dp[i][0]
            # dp[i+1][1] %= MOD
        if S[i] == "B" or S[i] == "?":
            dp[i + 1][2] += dp[i][1]
            # dp[i+1][2] %= MOD
        if S[i] == "C" or S[i] == "?":
            dp[i + 1][3] += dp[i][2]
            # dp[i+1][3] %= MOD
    print((dp[N][3] % MOD))
    return

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

    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == "__main__":
    main()


Input:
import numpy as np

import sys

n = int(eval(input()))

arr = np.array(list(map(int, input().split())))

arr.sort()

arr_cs = arr.cumsum()

ans = 0

for i in range(n - 1):

    if arr_cs[i] * 2 < arr[i + 1]:

        ans = i + 1

else:

    print((n - ans))

from itertools import accumulate

n = int(eval(input()))

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

arr.sort()

# 1つ前までの累積和の2倍がその時点の要素の大きさに達しているかどうか

cumsum = list(accumulate(arr))

result = []

for x, y in zip(arr[1:], cumsum[:-1]):

    if x <= y * 2:

        result.append(True)

    else:

        result.append(False)

if all(result):

    ans = n

else:

    ans = result[::-1].index(False) + 1

print(ans)

-arr = np.array(list(map(int, input().split())))

+# 1つ前までの累積和の2倍がその時点の要素の大きさに達しているかどうか

+    ans = result[::-1].index(False) + 1


Input:
import sys

input=sys.stdin.buffer.readline

sys.setrecursionlimit(10**9)

n=int(input())

edges=[[] for i in range(n)]

for i in range(n-1):

    a,s,w=map(int,input().split())

    edges[a-1].append([s-1,w]);edges[s-1].append([a-1,w])

colors=[-1]*n

colors[0]=1

def dfs(now):

    for to,cost in edges[now]:

        if colors[to]==-1:

            colors[to]=(cost+colors[now])%2

            dfs(to)

dfs(0)

print(*colors,sep="\n")

import sys

input=sys.stdin.buffer.readline

sys.setrecursionlimit(10**9)

N = int(input())

# v = [list(map(int, input().split())) for _ in range(N-1)]

edge = [[] for _ in range(N)]

for i in range(N-1):

    v1, v2, w = map(int, input().split())

    edge[v1-1].append((v2-1, w))

    edge[v2-1].append((v1-1, w))

color = [-1 for _ in range(N)]

color[0] = 1

def dfs(x):

    for v, w in edge[x]:

        if color[v] == -1:

            color[v] = (w + color[x])%2

            dfs(v)

dfs(0)

print(*color, sep="\n")

import sys

input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
n = int(input())
edges = [[] for i in range(n)]
for i in range(n - 1):
    a, s, w = map(int, input().split())
    edges[a - 1].append([s - 1, w])
    edges[s - 1].append([a - 1, w])
colors = [-1] * n
colors[0] = 1

def dfs(now):
    for to, cost in edges[now]:
        if colors[to] == -1:
            colors[to] = (cost + colors[now]) % 2
            dfs(to)

dfs(0)
print(*colors, sep="\n")

import sys

input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
N = int(input())
# v = [list(map(int, input().split())) for _ in range(N-1)]
edge = [[] for _ in range(N)]
for i in range(N - 1):
    v1, v2, w = map(int, input().split())
    edge[v1 - 1].append((v2 - 1, w))
    edge[v2 - 1].append((v1 - 1, w))
color = [-1 for _ in range(N)]
color[0] = 1

def dfs(x):
    for v, w in edge[x]:
        if color[v] == -1:
            color[v] = (w + color[x]) % 2
            dfs(v)

dfs(0)
print(*color, sep="\n")

-    a, s, w = map(int, input().split())

+# v = [list(map(int, input().split())) for _ in range(N-1)]

+    v1, v2, w = map(int, input().split())

-            colors[to] = (cost + colors[now]) % 2

+            color[v] = (w + color[x]) % 2


Input:
if __name__ == "__main__":

    S = eval(input())

    ans = 0

    bcount = 0

    for i in range(len(S)):

        if S[i] == 'B':

            bcount += 1

        else:

            ans += bcount

    print(ans)

if __name__ == "__main__":

    s = eval(input())

    bcount = 0

    ans = 0

    for ss in s:

        if ss == 'B':

            bcount += 1

        else:

            ans += bcount

    print(ans)

if __name__ == "__main__":
    S = eval(input())
    ans = 0
    bcount = 0
    for i in range(len(S)):
        if S[i] == "B":
            bcount += 1
        else:
            ans += bcount
    print(ans)

if __name__ == "__main__":
    s = eval(input())
    bcount = 0
    ans = 0
    for ss in s:
        if ss == "B":
            bcount += 1
        else:
            ans += bcount
    print(ans)

-    S = eval(input())
+    s = eval(input())
+    bcount = 0
-    bcount = 0
-    for i in range(len(S)):
-        if S[i] == "B":
+    for ss in s:
+        if ss == "B":


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

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

tmp = sum([(p * (p + 1) // 2) / p for p in P[:K]])

ans = tmp

for i in range(N - K):

    tmp -= (P[i] * (P[i] + 1) // 2) / P[i]

    tmp += (P[K + i] * (P[K + i] + 1) // 2) / P[K + i]

    ans = max(ans, tmp)

print(ans)

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

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

tmp = sum([(p + 1) / 2 for p in P[:K]])

ans = tmp

for i in range(N - K):

    tmp = tmp - (P[i] + 1) / 2 + (P[K + i] + 1) / 2

    ans = max(ans, tmp)

print(ans)

+tmp = sum([(p + 1) / 2 for p in P[:K]])


Input:
from fractions import gcd

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

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

P.append(X)

P.sort()

x0 = P[0]

P = [x - x0 for x in P]

ans = 0

for x in P:

    ans = gcd(ans, x)

print(ans)

from fractions import gcd

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

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

x0 = min(min(P), X)

P = [x - x0 for x in P]

ans = X - x0

for x in P:

    ans = gcd(ans, x)

print(ans)

-P.append(X)
-P.sort()
-x0 = P[0]
+x0 = min(min(P), X)
-ans = 0
+ans = X - x0


Input:
import sys

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

def resolve():

    s=eval(input())

    t='CODEFESTIVAL2016'

    cnt=0

    for i in range(16):

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

            cnt+=1

    print(cnt)

resolve()

import sys

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

def resolve():

    s=eval(input())

    t='CODEFESTIVAL2016'

    cnt=0

    for ss,tt in zip(s,t):

        if ss!=tt:

            cnt+=1

    print(cnt)

resolve()

import sys

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

def resolve():
    s = eval(input())
    t = "CODEFESTIVAL2016"
    cnt = 0
    for i in range(16):
        if s[i] != t[i]:
            cnt += 1
    print(cnt)

resolve()

import sys

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

def resolve():
    s = eval(input())
    t = "CODEFESTIVAL2016"
    cnt = 0
    for ss, tt in zip(s, t):
        if ss != tt:
            cnt += 1
    print(cnt)

resolve()

-    for i in range(16):
-        if s[i] != t[i]:
+    for ss, tt in zip(s, t):
+        if ss != tt:


Input:
from sys import *

from collections import deque

H, W = list(map(int, stdin.readline().split()))

personY, personX = list(map(int, stdin.readline().split()))

gH, gW = list(map(int, stdin.readline().split()))

grid = [list(stdin.readline().strip()) for x in range(H)]

visited = [ [10**10] * W for i in range(H)]

options = deque([[personY-1, personX-1]])

visited[personY-1][personX-1] = 0

while(options):

    y,x = options.popleft()

    if y+1 < H and  grid[y+1][x] == ".":

        if visited[y+1][x] > visited[y][x]:

            options.appendleft((y+1, x))

            visited[y+1][x] = visited[y][x]

    if  y-1 >= 0 and grid[y-1][x] == ".":

        if visited[y-1][x] > visited[y][x]:

            options.appendleft((y-1, x))

            visited[y-1][x] = visited[y][x]

    if x+1 < W and grid[y][x+1] == ".":

        if visited[y][x+1] > visited[y][x]:

            options.appendleft((y, x+1))

            visited[y][x+1] = visited[y][x]

    if x-1 >= 0 and grid[y][x-1] == ".":

        if visited[y][x-1] > visited[y][x]:

            options.appendleft((y, x-1))

            visited[y][x-1] = visited[y][x]

   #-------------------------------------------

    for Y,X in [(2,-2),(2,-1),(2,0),(2,1),(2,2), (1,-2),(1,-1),(1,1),(1,2), (0,-2),(0,2), (-1,-2),(-1,-1),(-1,1),(-1,2), (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2)]:

       if x+X >= 0 and x+X < W and y+Y >= 0 and y+Y < H and grid[y+Y][x+X] == ".":

           if visited[y+Y][x+X] > visited[y][x] +1:

               options.append((y+Y, x+X))

               visited[y+Y][x+X] = visited[y][x]+1

print((-1 if visited[gH-1][gW-1] == 10**10 else visited[gH-1][gW-1] ))

from sys import *

from collections import deque

H, W = list(map(int, stdin.readline().split()))

personY, personX = list(map(int, stdin.readline().split()))

gH, gW = list(map(int, stdin.readline().split()))

grid = [eval(input()) for x in range(H)]

visited = [[10**10] * W for i in range(H)]

options = deque([[personY-1, personX-1]])

visited[personY-1][personX-1] = 0

while(options):

    y,x = options.popleft()

    if y+1 < H and  grid[y+1][x] == ".":

        if visited[y+1][x] > visited[y][x]:

            options.appendleft((y+1, x))

            visited[y+1][x] = visited[y][x]

    if  y-1 >= 0 and grid[y-1][x] == ".":

        if visited[y-1][x] > visited[y][x]:

            options.appendleft((y-1, x))

            visited[y-1][x] = visited[y][x]

    if x+1 < W and grid[y][x+1] == ".":

        if visited[y][x+1] > visited[y][x]:

            options.appendleft((y, x+1))

            visited[y][x+1] = visited[y][x]

    if x-1 >= 0 and grid[y][x-1] == ".":

        if visited[y][x-1] > visited[y][x]:

            options.appendleft((y, x-1))

            visited[y][x-1] = visited[y][x]

   #-------------------------------------------

    for Y,X in [(2,-2),(2,-1),(2,0),(2,1),(2,2), (1,-2),(1,-1),(1,1),(1,2), (0,-2),(0,2), (-1,-2),(-1,-1),(-1,1),(-1,2), (-2,-2),(-2,-1),(-2,0),(-2,1),(-2,2)]:

       if x+X >= 0 and x+X < W and y+Y >= 0 and y+Y < H and grid[y+Y][x+X] == ".":

           if visited[y+Y][x+X] > visited[y][x] +1:

               options.append((y+Y, x+X))

               visited[y+Y][x+X] = visited[y][x]+1

print((-1 if visited[gH-1][gW-1] == 10**10 else visited[gH-1][gW-1] ))

from sys import *
from collections import deque

H, W = list(map(int, stdin.readline().split()))
personY, personX = list(map(int, stdin.readline().split()))
gH, gW = list(map(int, stdin.readline().split()))
grid = [list(stdin.readline().strip()) for x in range(H)]
visited = [[10**10] * W for i in range(H)]
options = deque([[personY - 1, personX - 1]])
visited[personY - 1][personX - 1] = 0
while options:
    y, x = options.popleft()
    if y + 1 < H and grid[y + 1][x] == ".":
        if visited[y + 1][x] > visited[y][x]:
            options.appendleft((y + 1, x))
            visited[y + 1][x] = visited[y][x]
    if y - 1 >= 0 and grid[y - 1][x] == ".":
        if visited[y - 1][x] > visited[y][x]:
            options.appendleft((y - 1, x))
            visited[y - 1][x] = visited[y][x]
    if x + 1 < W and grid[y][x + 1] == ".":
        if visited[y][x + 1] > visited[y][x]:
            options.appendleft((y, x + 1))
            visited[y][x + 1] = visited[y][x]
    if x - 1 >= 0 and grid[y][x - 1] == ".":
        if visited[y][x - 1] > visited[y][x]:
            options.appendleft((y, x - 1))
            visited[y][x - 1] = visited[y][x]
    # -------------------------------------------
    for Y, X in [
        (2, -2),
        (2, -1),
        (2, 0),
        (2, 1),
        (2, 2),
        (1, -2),
        (1, -1),
        (1, 1),
        (1, 2),
        (0, -2),
        (0, 2),
        (-1, -2),
        (-1, -1),
        (-1, 1),
        (-1, 2),
        (-2, -2),
        (-2, -1),
        (-2, 0),
        (-2, 1),
        (-2, 2),
    ]:
        if (
            x + X >= 0
            and x + X < W
            and y + Y >= 0
            and y + Y < H
            and grid[y + Y][x + X] == "."
        ):
            if visited[y + Y][x + X] > visited[y][x] + 1:
                options.append((y + Y, x + X))
                visited[y + Y][x + X] = visited[y][x] + 1
print((-1 if visited[gH - 1][gW - 1] == 10**10 else visited[gH - 1][gW - 1]))

from sys import *
from collections import deque

H, W = list(map(int, stdin.readline().split()))
personY, personX = list(map(int, stdin.readline().split()))
gH, gW = list(map(int, stdin.readline().split()))
grid = [eval(input()) for x in range(H)]
visited = [[10**10] * W for i in range(H)]
options = deque([[personY - 1, personX - 1]])
visited[personY - 1][personX - 1] = 0
while options:
    y, x = options.popleft()
    if y + 1 < H and grid[y + 1][x] == ".":
        if visited[y + 1][x] > visited[y][x]:
            options.appendleft((y + 1, x))
            visited[y + 1][x] = visited[y][x]
    if y - 1 >= 0 and grid[y - 1][x] == ".":
        if visited[y - 1][x] > visited[y][x]:
            options.appendleft((y - 1, x))
            visited[y - 1][x] = visited[y][x]
    if x + 1 < W and grid[y][x + 1] == ".":
        if visited[y][x + 1] > visited[y][x]:
            options.appendleft((y, x + 1))
            visited[y][x + 1] = visited[y][x]
    if x - 1 >= 0 and grid[y][x - 1] == ".":
        if visited[y][x - 1] > visited[y][x]:
            options.appendleft((y, x - 1))
            visited[y][x - 1] = visited[y][x]
    # -------------------------------------------
    for Y, X in [
        (2, -2),
        (2, -1),
        (2, 0),
        (2, 1),
        (2, 2),
        (1, -2),
        (1, -1),
        (1, 1),
        (1, 2),
        (0, -2),
        (0, 2),
        (-1, -2),
        (-1, -1),
        (-1, 1),
        (-1, 2),
        (-2, -2),
        (-2, -1),
        (-2, 0),
        (-2, 1),
        (-2, 2),
    ]:
        if (
            x + X >= 0
            and x + X < W
            and y + Y >= 0
            and y + Y < H
            and grid[y + Y][x + X] == "."
        ):
            if visited[y + Y][x + X] > visited[y][x] + 1:
                options.append((y + Y, x + X))
                visited[y + Y][x + X] = visited[y][x] + 1
print((-1 if visited[gH - 1][gW - 1] == 10**10 else visited[gH - 1][gW - 1]))

-grid = [list(stdin.readline().strip()) for x in range(H)]

+grid = [eval(input()) for x in range(H)]


Input:
import sys

input = sys.stdin.readline

N = int(eval(input()))

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

dp = [[0 for _ in range(2*N+2)] for _ in range(N)]

dp[0][N-1] = 1 - prob_table[0]

dp[0][N+1] =   prob_table[0]

for i in range(1,N):

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

		if(j > 0 and j < 2*N+1):

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

		elif(j <= 0):

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

		else :

			dp[i][j] = dp[i-1][j-1]*prob_table[i]

print((sum(dp[N-1][N+1:])))

import sys

input = sys.stdin.readline

N = int(eval(input()))

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

dp = [[0 for _ in range(N+1)] for _ in range(N+1)]

dp[0][0] = 1

for i in range(0,N):

	for j in range(i+1):

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

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

print((sum(dp[N][N//2+1:])))

import sys

input = sys.stdin.readline
N = int(eval(input()))
prob_table = list(map(float, input().split()))
dp = [[0 for _ in range(2 * N + 2)] for _ in range(N)]
dp[0][N - 1] = 1 - prob_table[0]
dp[0][N + 1] = prob_table[0]
for i in range(1, N):
    for j in range(N - i - 1, N + i + 2):
        if j > 0 and j < 2 * N + 1:
            dp[i][j] = dp[i - 1][j - 1] * prob_table[i] + dp[i - 1][j + 1] * (
                1 - prob_table[i]
            )
        elif j <= 0:
            dp[i][j] = dp[i - 1][j + 1] * (1 - prob_table[i])
        else:
            dp[i][j] = dp[i - 1][j - 1] * prob_table[i]
print((sum(dp[N - 1][N + 1 :])))

import sys

input = sys.stdin.readline
N = int(eval(input()))
prob_table = list(map(float, input().split()))
dp = [[0 for _ in range(N + 1)] for _ in range(N + 1)]
dp[0][0] = 1
for i in range(0, N):
    for j in range(i + 1):
        dp[i + 1][j + 1] += dp[i][j] * prob_table[i]
        dp[i + 1][j] += dp[i][j] * (1 - prob_table[i])
print((sum(dp[N][N // 2 + 1 :])))

-dp = [[0 for _ in range(2 * N + 2)] for _ in range(N)]

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

-            dp[i][j] = dp[i - 1][j - 1] * prob_table[i]

+dp = [[0 for _ in range(N + 1)] for _ in range(N + 1)]


Input:
def main():

    import sys

    input = sys.stdin.readline

    from itertools import accumulate

    def e(dice):

        ans = 0

        for r in range(1, dice+1):

            ans += r /dice

        return ans

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

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

    p_cum = [0] + list(accumulate(p))

    ma = 0

    ind = 0

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

        temp = p_cum[i] - p_cum[i-k]

        if ma < temp:

            ma = temp

            ind = i

    x = p[ind-k:ind]

    print((sum(e(d) for d in x)))

if __name__ == '__main__':

    main()

from itertools import accumulate

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

p = [0] + list(accumulate([(int(d) + 1) / 2 for d in input().split()]))

ans = 0

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

    ans = max(ans, p[i] - p[i-k])

print(ans)

def main():
    import sys

    input = sys.stdin.readline
    from itertools import accumulate

    def e(dice):
        ans = 0
        for r in range(1, dice + 1):
            ans += r / dice
        return ans

    n, k = list(map(int, input().split()))
    p = list(map(int, input().split()))
    p_cum = [0] + list(accumulate(p))
    ma = 0
    ind = 0
    for i in range(k, n + 1):
        temp = p_cum[i] - p_cum[i - k]
        if ma < temp:
            ma = temp
            ind = i
    x = p[ind - k : ind]
    print((sum(e(d) for d in x)))

if __name__ == "__main__":
    main()

from itertools import accumulate

n, k = list(map(int, input().split()))
p = [0] + list(accumulate([(int(d) + 1) / 2 for d in input().split()]))
ans = 0
for i in range(k, n + 1):
    ans = max(ans, p[i] - p[i - k])
print(ans)

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

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

+p = [0] + list(accumulate([(int(d) + 1) / 2 for d in input().split()]))


Input:
import sys

class BinaryTree:

    def __init__(self):

        self.root = None

    def b_insert(self,x):

        if self.root is None:

            self.root = Node(x)

            return

        node = None

        root = self.root

        while root is not None:

            node = root

            if x == root.data:

                return

            elif x < root.data:

                root = root.left

            else:

                root = root.right

        if node is None:

            # print("center",x)

            node = Node(x)

        elif node.data < x:

            # print("right",x)

            node.right = Node(x)

        else:

            # print("left",x)

            node.left = Node(x)

    def b_inorder(self):

        return inorder(self.root)

    def b_preorder(self):

        return preorder(self.root)

class Node:

    def __init__(self,x):

        self.data = x

        self.left = None

        self.right = None

def inorder(node):

    nodelist = []

    if node.left:

        nodelist += inorder(node.left)

    nodelist += [node.data]

    if node.right:

        nodelist += inorder(node.right)

    return nodelist

def preorder(node):

    nodelist = [node.data]

    if node.left:

        nodelist += preorder(node.left)

    if node.right:

        nodelist += preorder(node.right)

    return nodelist

line = sys.stdin.readline()

bfs = BinaryTree()

for temp in sys.stdin:

    if temp[0] == 'i':

        command,num = (n for n in temp.split(" "))

        bfs.b_insert(int(num))

    else:

        print("",end=" ")

        print(*bfs.b_inorder())

        print("",end=" ")

        print(*bfs.b_preorder())

class BinarySearchTree:

    def __init__(self):

        self.root = None

    def insert(self, x):

        node = self.Node(x)

        if self.root is None:

            self.root = node

        else:

            here = self.root

            #

            temp = None

            while here is not None:

                temp = here

                if x < here.node:

                    here = here.left

                elif x > here.node:

                    here = here.right

            if x < temp.node:

                temp.left = node

            elif x > temp.node:

                temp.right = node

    def inorder(self, answer, address = "root"):

        if address is "root":

            address = self.root

        elif address is None:

            return

        self.inorder(answer, address.left)

        answer.append(address.node)

        self.inorder(answer, address.right)

    def preorder(self, answer, address = "root"):

        if address is "root":

            address = self.root

        elif address is None:

            return

        answer.append(address.node)

        self.preorder(answer, address.left)

        self.preorder(answer, address.right)

    class Node:

        def __init__(self, x):

            self.node = x

            self.left = None

            self.right = None

query = int(input())

bt = BinarySearchTree()

for _ in range(query):

    command = input()

    if command[0] == "i":

        bt.insert(int(command.split(" ")[1]))

    else:

        a = []

        bt.inorder(a)

        print(" ", end = "")

        print(*a)

        a = []

        bt.preorder(a)

        print(" ", end = "")

        print(*a)

import sys

class BinaryTree:
    def __init__(self):
        self.root = None

    def b_insert(self, x):
        if self.root is None:
            self.root = Node(x)
            return
        node = None
        root = self.root
        while root is not None:
            node = root
            if x == root.data:
                return
            elif x < root.data:
                root = root.left
            else:
                root = root.right
        if node is None:
            # print("center",x)
            node = Node(x)
        elif node.data < x:
            # print("right",x)
            node.right = Node(x)
        else:
            # print("left",x)
            node.left = Node(x)

    def b_inorder(self):
        return inorder(self.root)

    def b_preorder(self):
        return preorder(self.root)

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

def inorder(node):
    nodelist = []
    if node.left:
        nodelist += inorder(node.left)
    nodelist += [node.data]
    if node.right:
        nodelist += inorder(node.right)
    return nodelist

def preorder(node):
    nodelist = [node.data]
    if node.left:
        nodelist += preorder(node.left)
    if node.right:
        nodelist += preorder(node.right)
    return nodelist

line = sys.stdin.readline()
bfs = BinaryTree()
for temp in sys.stdin:
    if temp[0] == "i":
        command, num = (n for n in temp.split(" "))
        bfs.b_insert(int(num))
    else:
        print("", end=" ")
        print(*bfs.b_inorder())
        print("", end=" ")
        print(*bfs.b_preorder())

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, x):
        node = self.Node(x)
        if self.root is None:
            self.root = node
        else:
            here = self.root
            #
            temp = None
            while here is not None:
                temp = here
                if x < here.node:
                    here = here.left
                elif x > here.node:
                    here = here.right
            if x < temp.node:
                temp.left = node
            elif x > temp.node:
                temp.right = node

    def inorder(self, answer, address="root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        self.inorder(answer, address.left)
        answer.append(address.node)
        self.inorder(answer, address.right)

    def preorder(self, answer, address="root"):
        if address is "root":
            address = self.root
        elif address is None:
            return
        answer.append(address.node)
        self.preorder(answer, address.left)
        self.preorder(answer, address.right)

    class Node:
        def __init__(self, x):
            self.node = x
            self.left = None
            self.right = None

query = int(input())
bt = BinarySearchTree()
for _ in range(query):
    command = input()
    if command[0] == "i":
        bt.insert(int(command.split(" ")[1]))
    else:
        a = []
        bt.inorder(a)
        print(" ", end="")
        print(*a)
        a = []
        bt.preorder(a)
        print(" ", end="")
        print(*a)

+    def inorder(self, answer, address="root"):

+        self.inorder(answer, address.left)

+        self.inorder(answer, address.right)

+    def preorder(self, answer, address="root"):

+        self.preorder(answer, address.left)

+        self.preorder(answer, address.right)

-        nodelist += inorder(node.right)

-        nodelist += preorder(node.left)

-        nodelist += preorder(node.right)

-        command, num = (n for n in temp.split(" "))

+        bt.insert(int(command.split(" ")[1]))


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

left = 1

right = N

for _ in range(M):

    l, r = list(map(int, input().split()))

    if left < l:

        left = l

    if right > r:

        right = r

ans = right - left

print((ans + 1 if ans >= 0 else 0))

def main():

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

    left = 1

    right = N

    for _ in range(M):

        l, r = list(map(int, input().split()))

        if left < l:

            left = l

        if right > r:

            right = r

    ans = right - left

    print((ans + 1 if ans >= 0 else 0))

main()

-    l, r = list(map(int, input().split()))

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

+        l, r = list(map(int, input().split()))

+    print((ans + 1 if ans >= 0 else 0))


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

if l > 0:

    c = l

elif l + n - 1 < 0:

    c = l + n - 1

else:

    c = 0

print((l * n + n * (n - 1) // 2 - c))

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

a, b = sorted([l, l + n - 1])

print((sum(range((a + 1 if a > 0 else a),

                (b - 1 if b < 0 else b) + 1))))

+print((sum(range((a + 1 if a > 0 else a), (b - 1 if b < 0 else b) + 1))))


Input:
def main():

  n,k = input_list()

  a = input_list()

  ans = 0

  r = 1

  while True:

    r += k-1

    ans += 1

    if r >= n:

      break

  print(ans)

def input_list():

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

def input_list_str():

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

def lcm_base(x, y):

    return (x * y) // fractions.gcd(x, y)

def lcm_list(numbers):

    return reduce(lcm_base, numbers, 1)

def gcd(*numbers):

    return reduce(fractions.gcd, numbers)

def gcd_list(numbers):

    return reduce(fractions.gcd, numbers)

# 2で割り切れる回数

def divide_two(arg):

  c = 0

  while True:

    if c >= 2:

      break

    if arg % 2 != 0:

      break

    arg //= 2

    c += 1

  return c

import math

import fractions

import collections

from functools import reduce

main()

import math

def main():

    n, k = input_list()

    a = input_list()

    a = math.ceil((n-k)/(k-1))

    print((1+a))

def input_list():

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

if __name__ == "__main__":

    main()

def main():
    n, k = input_list()
    a = input_list()
    ans = 0
    r = 1
    while True:
        r += k - 1
        ans += 1
        if r >= n:
            break
    print(ans)

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

def input_list_str():
    return list(map(str, input().split()))

def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)

def gcd(*numbers):
    return reduce(fractions.gcd, numbers)

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)

# 2で割り切れる回数
def divide_two(arg):
    c = 0
    while True:
        if c >= 2:
            break
        if arg % 2 != 0:
            break
        arg //= 2
        c += 1
    return c

import math
import fractions
import collections
from functools import reduce

main()

import math

def main():
    n, k = input_list()
    a = input_list()
    a = math.ceil((n - k) / (k - 1))
    print((1 + a))

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

if __name__ == "__main__":
    main()

-    return list(map(str, input().split()))

-    return (x * y) // fractions.gcd(x, y)

-    return reduce(lcm_base, numbers, 1)

-    return reduce(fractions.gcd, numbers)

-    return reduce(fractions.gcd, numbers)

-# 2で割り切れる回数


Input:
s = list(eval(input()))

print((2*min(s.count('0'),s.count('1'))))

s = eval(input())

print((2*min(s.count('0'),s.count('1'))))

s = list(eval(input()))
print((2 * min(s.count("0"), s.count("1"))))

s = eval(input())
print((2 * min(s.count("0"), s.count("1"))))

-s = list(eval(input()))
+s = eval(input())


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

'''Snippets for lcm.

Available functions:

- lcm: Compute least common multiple of a and b.

'''

def lcm(a: int, b: int) -> int:

    '''Compute least common multiple of a and b.

    Args:

        a: Int of number (greater than 0).

        b: Int of number (greater than 0).

    Returns:

        least common multiple.

    Landau notation: O(log n)

    See:

    https://gist.github.com/endolith/114336/eff2dc13535f139d0d6a2db68597fad2826b53c3

    https://docs.python.org/3/library/sys.html#sys.version_info

    '''

    from sys import version_info

    if version_info.major == 3 and version_info.minor >= 5:

        from math import gcd

    else:

        from fractions import gcd

    return a * b // gcd(a, b)

def main():

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

    l = lcm(c, d)

    x = b // c - (a - 1) // c

    y = b // d - (a - 1) // d

    z = b // l - (a - 1) // l

    w = b - a + 1

    if c % d == 0 or d % c == 0:

        print((w - x))

    else:

        print((w - (x + y - z)))

if __name__ == '__main__':

    main()

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

'''Snippets for lcm.

Available functions:

- lcm: Compute least common multiple of a and b.

'''

def lcm(a: int, b: int) -> int:

    '''Compute least common multiple of a and b.

    Args:

        a: Int of number (greater than 0).

        b: Int of number (greater than 0).

    Returns:

        least common multiple.

    Landau notation: O(log n)

    See:

    https://gist.github.com/endolith/114336/eff2dc13535f139d0d6a2db68597fad2826b53c3

    https://docs.python.org/3/library/sys.html#sys.version_info

    '''

    from sys import version_info

    if version_info.major == 3 and version_info.minor >= 5:

        from math import gcd

    else:

        from fractions import gcd

    return a * b // gcd(a, b)

def main():

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

    l = lcm(c, d)

    x = b // c - (a - 1) // c

    y = b // d - (a - 1) // d

    z = b // l - (a - 1) // l

    w = b - a + 1

    print((w - (x + y - z)))

if __name__ == '__main__':

    main()

# -*- coding: utf-8 -*-
"""Snippets for lcm.
Available functions:
- lcm: Compute least common multiple of a and b.
"""

def lcm(a: int, b: int) -> int:
    """Compute least common multiple of a and b.
    Args:
        a: Int of number (greater than 0).
        b: Int of number (greater than 0).
    Returns:
        least common multiple.
    Landau notation: O(log n)
    See:
    https://gist.github.com/endolith/114336/eff2dc13535f139d0d6a2db68597fad2826b53c3
    https://docs.python.org/3/library/sys.html#sys.version_info
    """
    from sys import version_info

    if version_info.major == 3 and version_info.minor >= 5:
        from math import gcd
    else:
        from fractions import gcd
    return a * b // gcd(a, b)

def main():
    a, b, c, d = list(map(int, input().split()))
    l = lcm(c, d)
    x = b // c - (a - 1) // c
    y = b // d - (a - 1) // d
    z = b // l - (a - 1) // l
    w = b - a + 1
    if c % d == 0 or d % c == 0:
        print((w - x))
    else:
        print((w - (x + y - z)))

if __name__ == "__main__":
    main()

# -*- coding: utf-8 -*-
"""Snippets for lcm.
Available functions:
- lcm: Compute least common multiple of a and b.
"""

def lcm(a: int, b: int) -> int:
    """Compute least common multiple of a and b.
    Args:
        a: Int of number (greater than 0).
        b: Int of number (greater than 0).
    Returns:
        least common multiple.
    Landau notation: O(log n)
    See:
    https://gist.github.com/endolith/114336/eff2dc13535f139d0d6a2db68597fad2826b53c3
    https://docs.python.org/3/library/sys.html#sys.version_info
    """
    from sys import version_info

    if version_info.major == 3 and version_info.minor >= 5:
        from math import gcd
    else:
        from fractions import gcd
    return a * b // gcd(a, b)

def main():
    a, b, c, d = list(map(int, input().split()))
    l = lcm(c, d)
    x = b // c - (a - 1) // c
    y = b // d - (a - 1) // d
    z = b // l - (a - 1) // l
    w = b - a + 1
    print((w - (x + y - z)))

if __name__ == "__main__":
    main()