Input:
import sys

input=sys.stdin.readline

def main():

    N = int(eval(input()))

    F = []

    for _ in range(N):

        F.append(list(map(int, input().split())))

    P = []

    for _ in range(N):

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

    ans = -10**7*N

    for i in range(1, 1<<10):

        tmp = 0

        for s,f in enumerate(F):

            c = 0

            for j in range(10):

                if (i>>j)&1&f[j]:

                    c += 1

            tmp += P[s][c]

        ans = max(ans, tmp)

    print(ans)

if __name__ == '__main__':

    main()

import sys

input=sys.stdin.readline

def main():

    N = int(eval(input()))

    F = [int(input().replace(" ", ""), 2) for _ in range(N)]

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

    ans = -10**7*N

    for i in range(1, 1<<10):

        tmp = 0

        for j,f in enumerate(F):

            c = bin(i&f).count("1")

            tmp += P[j][c]

        ans = max(ans, tmp)

    print(ans)

if __name__ == '__main__':

    main()

import sys

input = sys.stdin.readline

def main():
    N = int(eval(input()))
    F = []
    for _ in range(N):
        F.append(list(map(int, input().split())))
    P = []
    for _ in range(N):
        P.append(list(map(int, input().split())))
    ans = -(10**7) * N
    for i in range(1, 1 << 10):
        tmp = 0
        for s, f in enumerate(F):
            c = 0
            for j in range(10):
                if (i >> j) & 1 & f[j]:
                    c += 1
            tmp += P[s][c]
        ans = max(ans, tmp)
    print(ans)

if __name__ == "__main__":
    main()

import sys

input = sys.stdin.readline

def main():
    N = int(eval(input()))
    F = [int(input().replace(" ", ""), 2) for _ in range(N)]
    P = [list(map(int, input().split())) for _ in range(N)]
    ans = -(10**7) * N
    for i in range(1, 1 << 10):
        tmp = 0
        for j, f in enumerate(F):
            c = bin(i & f).count("1")
            tmp += P[j][c]
        ans = max(ans, tmp)
    print(ans)

if __name__ == "__main__":
    main()

-        F.append(list(map(int, input().split())))

-        P.append(list(map(int, input().split())))

+    F = [int(input().replace(" ", ""), 2) for _ in range(N)]

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


Input:
import sys

# import re

import math

import collections

# import decimal

import bisect

import itertools

import fractions

# import functools

import copy

import heapq

import decimal

# import statistics

import queue

import numpy as np

sys.setrecursionlimit(10000001)

INF = 10 ** 16

# MOD = 10 ** 9 + 7

MOD = 998244353

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():

    def fast_pow(num, kata, mod):

        if kata == 0:

            return 1

        res = 1

        while kata > 0:

            if kata & 1 == 1:

                res = res * num % mod

            num = num * num % mod

            kata >>= 1

        return res

    def prepare(n, MOD):

        f = 1

        factorials = [1]

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

            f *= m

            f %= MOD

            factorials.append(f)

        inv = pow(f, MOD - 2, MOD)

        invs = [1] * (n + 1)

        invs[n] = inv

        for m in range(n, 1, -1):

            inv *= m

            inv %= MOD

            invs[m - 1] = inv

        return factorials, invs

    n, m, k = ns()

    p, i = prepare(n, MOD)

    result = 0

    for ki in range(k + 1):

        ans = 1

        ans *= m % MOD

        ans *= fast_pow(m - 1, n - 1 - ki, MOD)

        ans %= MOD

        ans *= p[n - 1] * i[ki] * i[n - 1 - ki]

        ans %= MOD

        result += ans

        result %= MOD

    print(result)

if __name__ == '__main__':

    main()

import sys

# import re

import math

import collections

# import decimal

import bisect

import itertools

import fractions

# import functools

import copy

import heapq

import decimal

# import statistics

import queue

# import numpy as np

# sys.setrecursionlimit(10000001)

INF = 10 ** 16

# MOD = 10 ** 9 + 7

MOD = 998244353

def ni(): return int(sys.stdin.readline())

def ns(): return list(map(int, sys.stdin.readline().split()))

def na(): return list(map(int, sys.stdin.readline().split()))

# ===CODE===

class ModCombination:

    # https://atcoder.jp/contests/abc167/submissions/13058694

    # https://ikatakos.com/pot/programming_algorithm/number_theory/mod_combination

    def __init__(self, maxN, MOD):

        self._maxN = maxN

        self._MOD = MOD

        self.facts = [1]

        self.invs = [1]*(self._maxN+1)

        fact = 1

        for i in range(1, self._maxN+1):

            fact *= i

            fact %= self._MOD

            self.facts.append(fact)

        inv = pow(fact, self._MOD-2, self._MOD)

        self.invs[self._maxN] = inv

        for i in range(self._maxN, 1, -1):

            inv *= i

            inv %= self._MOD

            self.invs[i-1] = inv

    def nCr(self, n, r):

        return self.facts[n]*self.invs[r]*self.invs[n-r] % self._MOD

def main():

    n, m, k = ns()

    mc = ModCombination(n, MOD)

    result = 0

    for ki in range(k + 1):

        ans = 1

        ans *= m % MOD

        ans *= pow(m - 1, n - 1 - ki, MOD)

        ans %= MOD

        ans *= mc.nCr(n-1, ki)

        ans %= MOD

        result += ans

        result %= MOD

    print(result)

if __name__ == '__main__':

    main()

import sys

# import re
import math
import collections

# import decimal
import bisect
import itertools
import fractions

# import functools
import copy
import heapq
import decimal

# import statistics
import queue
import numpy as np

sys.setrecursionlimit(10000001)
INF = 10**16
# MOD = 10 ** 9 + 7
MOD = 998244353
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():
    def fast_pow(num, kata, mod):
        if kata == 0:
            return 1
        res = 1
        while kata > 0:
            if kata & 1 == 1:
                res = res * num % mod
            num = num * num % mod
            kata >>= 1
        return res

    def prepare(n, MOD):
        f = 1
        factorials = [1]
        for m in range(1, n + 1):
            f *= m
            f %= MOD
            factorials.append(f)
        inv = pow(f, MOD - 2, MOD)
        invs = [1] * (n + 1)
        invs[n] = inv
        for m in range(n, 1, -1):
            inv *= m
            inv %= MOD
            invs[m - 1] = inv
        return factorials, invs

    n, m, k = ns()
    p, i = prepare(n, MOD)
    result = 0
    for ki in range(k + 1):
        ans = 1
        ans *= m % MOD
        ans *= fast_pow(m - 1, n - 1 - ki, MOD)
        ans %= MOD
        ans *= p[n - 1] * i[ki] * i[n - 1 - ki]
        ans %= MOD
        result += ans
        result %= MOD
    print(result)

if __name__ == "__main__":
    main()

import sys

# import re
import math
import collections

# import decimal
import bisect
import itertools
import fractions

# import functools
import copy
import heapq
import decimal

# import statistics
import queue

# import numpy as np
# sys.setrecursionlimit(10000001)
INF = 10**16
# MOD = 10 ** 9 + 7
MOD = 998244353

def ni():
    return int(sys.stdin.readline())

def ns():
    return list(map(int, sys.stdin.readline().split()))

def na():
    return list(map(int, sys.stdin.readline().split()))

# ===CODE===
class ModCombination:
    # https://atcoder.jp/contests/abc167/submissions/13058694
    # https://ikatakos.com/pot/programming_algorithm/number_theory/mod_combination
    def __init__(self, maxN, MOD):
        self._maxN = maxN
        self._MOD = MOD
        self.facts = [1]
        self.invs = [1] * (self._maxN + 1)
        fact = 1
        for i in range(1, self._maxN + 1):
            fact *= i
            fact %= self._MOD
            self.facts.append(fact)
        inv = pow(fact, self._MOD - 2, self._MOD)
        self.invs[self._maxN] = inv
        for i in range(self._maxN, 1, -1):
            inv *= i
            inv %= self._MOD
            self.invs[i - 1] = inv

    def nCr(self, n, r):
        return self.facts[n] * self.invs[r] * self.invs[n - r] % self._MOD

def main():
    n, m, k = ns()
    mc = ModCombination(n, MOD)
    result = 0
    for ki in range(k + 1):
        ans = 1
        ans *= m % MOD
        ans *= pow(m - 1, n - 1 - ki, MOD)
        ans %= MOD
        ans *= mc.nCr(n - 1, ki)
        ans %= MOD
        result += ans
        result %= MOD
    print(result)

if __name__ == "__main__":
    main()

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

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

+    return list(map(int, sys.stdin.readline().split()))

+    # https://atcoder.jp/contests/abc167/submissions/13058694

+    # https://ikatakos.com/pot/programming_algorithm/number_theory/mod_combination

+        self.invs = [1] * (self._maxN + 1)

+        for i in range(1, self._maxN + 1):

+        inv = pow(fact, self._MOD - 2, self._MOD)

+        for i in range(self._maxN, 1, -1):

+        return self.facts[n] * self.invs[r] * self.invs[n - r] % self._MOD

-        ans *= fast_pow(m - 1, n - 1 - ki, MOD)

+        ans *= pow(m - 1, n - 1 - ki, MOD)


Input:
import sys

read = sys.stdin.read

readline = sys.stdin.readline

readlines = sys.stdin.readlines

sys.setrecursionlimit(10 ** 9)

INF = 1 << 60

MOD = 1000000007

def check(vec, init_pos, target_pos):

    base = 8000

    dp = [False] * 16001

    dp[init_pos + base] = True

    for i in range(len(vec)):

        dp, dp_prev = [False] * 16001, dp

        for j in range(16001):

            if (

                j - vec[i] >= 0

                and dp_prev[j - vec[i]]

                or j + vec[i] <= 16000

                and dp_prev[j + vec[i]]

            ):

                dp[j] = True

    return dp[target_pos + base]

def main():

    S = readline().strip()

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

    idx = len(S)

    for i, c in enumerate(S):

        if c == 'T':

            idx = i

            break

    init_x = idx

    step = [[0] for _ in range(2)]

    i = 0

    for c in S[idx:]:

        if c == 'T':

            i = 1 - i

            step[i].append(0)

        else:

            step[i][-1] += 1

    ok = check(step[0], init_x, x) and check(step[1], 0, y)

    if ok:

        print('Yes')

    else:

        print('No')

    return

if __name__ == '__main__':

    main()

import sys

read = sys.stdin.read

readline = sys.stdin.readline

readlines = sys.stdin.readlines

sys.setrecursionlimit(10 ** 9)

INF = 1 << 60

MOD = 1000000007

def check(vec, init_pos, target_pos):

    base = 8000

    dp = [False] * 16001

    dp[init_pos + base] = True

    for i in range(len(vec)):

        dp, dp_prev = [False] * 16001, dp

        for j in range(16001):

            if (

                j - vec[i] >= 0

                and dp_prev[j - vec[i]]

                or j + vec[i] <= 16000

                and dp_prev[j + vec[i]]

            ):

                dp[j] = True

    return dp[target_pos + base]

def main():

    S = readline().strip()

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

    idx = len(S)

    for i, c in enumerate(S):

        if c == 'T':

            idx = i

            break

    init_x = idx

    step = [[] for _ in range(2)]

    i = 0

    for c in S[idx:]:

        if c == 'T':

            i = 1 - i

            step[i].append(0)

        else:

            step[i][-1] += 1

    for row in step:

        row = [v for v in row if v != 0]

        if not row:

            row = [0]

    ok = check(step[0], init_x, x) and check(step[1], 0, y)

    if ok:

        print('Yes')

    else:

        print('No')

    return

if __name__ == '__main__':

    main()

import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10**9)
INF = 1 << 60
MOD = 1000000007

def check(vec, init_pos, target_pos):
    base = 8000
    dp = [False] * 16001
    dp[init_pos + base] = True
    for i in range(len(vec)):
        dp, dp_prev = [False] * 16001, dp
        for j in range(16001):
            if (
                j - vec[i] >= 0
                and dp_prev[j - vec[i]]
                or j + vec[i] <= 16000
                and dp_prev[j + vec[i]]
            ):
                dp[j] = True
    return dp[target_pos + base]

def main():
    S = readline().strip()
    x, y = list(map(int, readline().split()))
    idx = len(S)
    for i, c in enumerate(S):
        if c == "T":
            idx = i
            break
    init_x = idx
    step = [[0] for _ in range(2)]
    i = 0
    for c in S[idx:]:
        if c == "T":
            i = 1 - i
            step[i].append(0)
        else:
            step[i][-1] += 1
    ok = check(step[0], init_x, x) and check(step[1], 0, y)
    if ok:
        print("Yes")
    else:
        print("No")
    return

if __name__ == "__main__":
    main()

import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10**9)
INF = 1 << 60
MOD = 1000000007

def check(vec, init_pos, target_pos):
    base = 8000
    dp = [False] * 16001
    dp[init_pos + base] = True
    for i in range(len(vec)):
        dp, dp_prev = [False] * 16001, dp
        for j in range(16001):
            if (
                j - vec[i] >= 0
                and dp_prev[j - vec[i]]
                or j + vec[i] <= 16000
                and dp_prev[j + vec[i]]
            ):
                dp[j] = True
    return dp[target_pos + base]

def main():
    S = readline().strip()
    x, y = list(map(int, readline().split()))
    idx = len(S)
    for i, c in enumerate(S):
        if c == "T":
            idx = i
            break
    init_x = idx
    step = [[] for _ in range(2)]
    i = 0
    for c in S[idx:]:
        if c == "T":
            i = 1 - i
            step[i].append(0)
        else:
            step[i][-1] += 1
    for row in step:
        row = [v for v in row if v != 0]
        if not row:
            row = [0]
    ok = check(step[0], init_x, x) and check(step[1], 0, y)
    if ok:
        print("Yes")
    else:
        print("No")
    return

if __name__ == "__main__":
    main()

+        row = [v for v in row if v != 0]


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

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

ans=[0]*n

def f(x):

  c=[x[i-1]^x[i]for i in range(1,n)]

  k=[x[1:].count(1)%2]

  for i in c:

    k.append(k[-1]^i)

  return k

for i in range(31):

  t=1<<i

  x=[]

  for j in a:

    if t&j:x.append(1)

    else:x.append(0)

  m=f(x)

  for j in range(n):ans[j]+=t*m[j]

print((*ans))

n=int(eval(input()))

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

s=0

for i in a:s^=i

for i in a:print((s^i))

n = int(eval(input()))
a = list(map(int, input().split()))
ans = [0] * n

def f(x):
    c = [x[i - 1] ^ x[i] for i in range(1, n)]
    k = [x[1:].count(1) % 2]
    for i in c:
        k.append(k[-1] ^ i)
    return k

for i in range(31):
    t = 1 << i
    x = []
    for j in a:
        if t & j:
            x.append(1)
        else:
            x.append(0)
    m = f(x)
    for j in range(n):
        ans[j] += t * m[j]
print((*ans))

n = int(eval(input()))
a = list(map(int, input().split()))
s = 0
for i in a:
    s ^= i
for i in a:
    print((s ^ i))

-    c = [x[i - 1] ^ x[i] for i in range(1, n)]


Input:
n = int(eval(input()))  #スペース抜きの複数行,１文字ずつ

A = []

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

    if i % 15 == 0:

        A.append(0)

    elif i % 3 == 0:

        A.append(0)

    elif i % 5 == 0:

        A.append(0)

    else:

        A.append(i)

print((sum(A)))

N = int(eval(input()))  #スペース抜きの複数行,１文字ずつ

A = []

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

  if i % 3 == 0:

    A.append(0)

  elif i % 5 == 0:

    A.append(0)

  else:

    A.append(i)

print((sum(A)))

n = int(eval(input()))  # スペース抜きの複数行,１文字ずつ
A = []
for i in range(1, n + 1):
    if i % 15 == 0:
        A.append(0)
    elif i % 3 == 0:
        A.append(0)
    elif i % 5 == 0:
        A.append(0)
    else:
        A.append(i)
print((sum(A)))

N = int(eval(input()))  # スペース抜きの複数行,１文字ずつ
A = []
for i in range(1, N + 1):
    if i % 3 == 0:
        A.append(0)
    elif i % 5 == 0:
        A.append(0)
    else:
        A.append(i)
print((sum(A)))

-n = int(eval(input()))  # スペース抜きの複数行,１文字ずつ

+N = int(eval(input()))  # スペース抜きの複数行,１文字ずつ


Input:
n,k,*v=list(map(int,open(0).read().split()))

motimono=[]

ans=[]

v*=2

for j in range(1,min(n,k)+1):

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

        motimono=v[i:i+j]

        ans.append(sum(motimono))

        motimono.sort()

        for i in range(k-j):

            if len(motimono)>0:

                del motimono[0]

            ans.append(sum(motimono))

print((max(ans)))

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

motimono=[]

ans=[]

v*=2

for j in range(1,min(n,k)+1):

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

        motimono=v[i:i+j]

        ans.append(sum(motimono))

        motimono.sort()

        for i in range(min(k-j,j)):

            del motimono[0]

            ans.append(sum(motimono))

print((max(ans)))

n, k, *v = list(map(int, open(0).read().split()))
motimono = []
ans = []
v *= 2
for j in range(1, min(n, k) + 1):
    for i in range(n - j, n + 1):
        motimono = v[i : i + j]
        ans.append(sum(motimono))
        motimono.sort()
        for i in range(k - j):
            if len(motimono) > 0:
                del motimono[0]
            ans.append(sum(motimono))
print((max(ans)))

n, k, *v = list(map(int, open(0).read().split()))
motimono = []
ans = []
v *= 2
for j in range(1, min(n, k) + 1):
    for i in range(n - j, n + 1):
        motimono = v[i : i + j]
        ans.append(sum(motimono))
        motimono.sort()
        for i in range(min(k - j, j)):
            del motimono[0]
            ans.append(sum(motimono))
print((max(ans)))

-        for i in range(k - j):
-            if len(motimono) > 0:
-                del motimono[0]
+        for i in range(min(k - j, j)):
+            del motimono[0]


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

d = 0

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

    c = str(i)

    e = True

    for j in range(len(c)//2):

        if c[j] != c[-j-1] and e:

            e = not e

    if e:

        d += 1

print(d)

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

d = 0

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

    c = str(i)

    if c[0] == c[-1] and c[1] == c[-2]:

        d += 1

print(d)

a, b = list(map(int, input().split()))
d = 0
for i in range(a, b + 1):
    c = str(i)
    e = True
    for j in range(len(c) // 2):
        if c[j] != c[-j - 1] and e:
            e = not e
    if e:
        d += 1
print(d)

a, b = list(map(int, input().split()))
d = 0
for i in range(a, b + 1):
    c = str(i)
    if c[0] == c[-1] and c[1] == c[-2]:
        d += 1
print(d)


Input:
from collections import Counter

N, li = int(eval(input())), list(map(int, input().split()))

cnt_dict, cnt_total = Counter(li), 0

for i in list(cnt_dict.items()):

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

for k in range(N):

    buf = cnt_dict[li[k]]

    print((cnt_total - buf*(buf-1)//2 + (buf-1)*(buf-2)//2))

from collections import Counter

N, li = int(eval(input())), list(map(int, input().split()))

cnt_dict, cnt_total = Counter(li), 0

cnt_total =sum([i[1] * (i[1]-1) // 2 for i in list(cnt_dict.items())])

for k in range(N):

    print((cnt_total - cnt_dict[li[k]]*(cnt_dict[li[k]]-1)//2 + (cnt_dict[li[k]]-1)*(cnt_dict[li[k]]-2)//2))

from collections import Counter

N, li = int(eval(input())), list(map(int, input().split()))
cnt_dict, cnt_total = Counter(li), 0
for i in list(cnt_dict.items()):
    cnt_total += i[1] * (i[1] - 1) // 2
for k in range(N):
    buf = cnt_dict[li[k]]
    print((cnt_total - buf * (buf - 1) // 2 + (buf - 1) * (buf - 2) // 2))

from collections import Counter

N, li = int(eval(input())), list(map(int, input().split()))
cnt_dict, cnt_total = Counter(li), 0
cnt_total = sum([i[1] * (i[1] - 1) // 2 for i in list(cnt_dict.items())])
for k in range(N):
    print(
        (
            cnt_total
            - cnt_dict[li[k]] * (cnt_dict[li[k]] - 1) // 2
            + (cnt_dict[li[k]] - 1) * (cnt_dict[li[k]] - 2) // 2
        )
    )

+cnt_total = sum([i[1] * (i[1] - 1) // 2 for i in list(cnt_dict.items())])

+            - cnt_dict[li[k]] * (cnt_dict[li[k]] - 1) // 2


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

S = list(eval(input()))

counter = 0

oversea= 1

for i,s in enumerate(S):

    if(s == 'a'):

        if(counter < (A + B)):

            print("Yes")

            counter+=1

        else:

            print("No")

    elif(s == 'b'):

        if(counter < (A + B) and  oversea <= B):

            print("Yes")

            counter+=1

            oversea +=1

        else:

            print("No")

    else:

        print("No")

def myAnswer(A: int, B: int, S: list) -> None:

    counter = 0

    foreignStu = 1

    for i, s in enumerate(S):

        if(s == 'a' and counter < (A + B)): #国内の学生で、カウンタの値が(A+B)未満なら通過

            print("Yes")

            counter += 1#カウンタの値を更新

        elif(s == 'b' and counter < (A + B) and foreignStu <= B): #海外の学生で、カウンタの値が(A+B)未満かつ海外学生の順位がB以下なら通過

            print("Yes")

            counter += 1

            foreignStu += 1

        else:

            print("No")

def main():

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

    S = list(eval(input()))

    myAnswer(A, B, S)

if __name__ == "__main__":

    main()

N, A, B = list(map(int, input().split()))
S = list(eval(input()))
counter = 0
oversea = 1
for i, s in enumerate(S):
    if s == "a":
        if counter < (A + B):
            print("Yes")
            counter += 1
        else:
            print("No")
    elif s == "b":
        if counter < (A + B) and oversea <= B:
            print("Yes")
            counter += 1
            oversea += 1
        else:
            print("No")
    else:
        print("No")

def myAnswer(A: int, B: int, S: list) -> None:
    counter = 0
    foreignStu = 1
    for i, s in enumerate(S):
        if s == "a" and counter < (A + B):  # 国内の学生で、カウンタの値が(A+B)未満なら通過
            print("Yes")
            counter += 1  # カウンタの値を更新
        elif (
            s == "b" and counter < (A + B) and foreignStu <= B
        ):  # 海外の学生で、カウンタの値が(A+B)未満かつ海外学生の順位がB以下なら通過
            print("Yes")
            counter += 1
            foreignStu += 1
        else:
            print("No")

def main():
    N, A, B = list(map(int, input().split()))
    S = list(eval(input()))
    myAnswer(A, B, S)

if __name__ == "__main__":
    main()

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

+def myAnswer(A: int, B: int, S: list) -> None:

+        if s == "a" and counter < (A + B):  # 国内の学生で、カウンタの値が(A+B)未満なら通過

+            s == "b" and counter < (A + B) and foreignStu <= B

+        ):  # 海外の学生で、カウンタの値が(A+B)未満かつ海外学生の順位がB以下なら通過

-        if counter < (A + B) and oversea <= B:

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


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

#print(N,K,L,D,T)

class UnionFind:

    def __init__(self, n: int) -> None:

        self.par = [i for i in range(n)]

        self.rank = [0] * n

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

        if self.par[x] == x:

            return x

        else:

            self.par[x] = self.find(self.par[x])

            return self.par[x]

    def unite(self, x: int, y: int) -> None:

        x = self.find(x)

        y = self.find(y)

        if self.rank[x] < self.rank[y]:

            self.par[x] = y

        else:

            self.par[y] = x

            if self.rank[x] == self.rank[y]:

                self.rank[x] += 1

    # 同じ集合に属するか判定

    #def same_check(self, x, y):

    #    return self.find(x) == self.find(y)

def uniteOne(num, uf):

    for _ in range(num):

        d0, d1 = list(map(int, input().split()))

        uf.unite(d0-1, d1-1)

uf_D = UnionFind(N)

uf_T = UnionFind(N)

uniteOne(K, uf_D)

uniteOne(L, uf_T)

from collections import Counter

keys = []

counts = Counter()

for i in range(N):

    key = uf_D.find(i), uf_T.find(i)

    keys.append(key)

    counts[key] += 1

print((*(counts[key] for key in keys)))

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

#print(N,K,L,D,T)

class UnionFind:

    def __init__(self, n: int) -> None:

        #マイナスならルートでその深さを表す。プラスならルートのノードを指す。

        self.nodes = [-1]*n

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

        if self.nodes[x] < 0:

            return x

        else:

            self.nodes[x] = self.find_root(self.nodes[x])

            return self.nodes[x]

    def unite(self, x: int, y: int) -> None:

        x, y = self.find_root(x), self.find_root(y)

        #浅い方につなぐ

        if (x != y):

            if (x < y):

                self.nodes[y] += self.nodes[x]

                self.nodes[x] = y

            else:

                self.nodes[x] += self.nodes[y]

                self.nodes[y] = x

    # 同じ集合に属するか判定

    #def same_check(self, x, y):

    #    return self.find(x) == self.find(y)

def uniteOne(num, uf):

    for _ in range(num):

        d0, d1 = list(map(int, input().split()))

        uf.unite(d0-1, d1-1)

uf_D = UnionFind(N)

uf_T = UnionFind(N)

uniteOne(K, uf_D)

uniteOne(L, uf_T)

pairs = []

for i in range(N):

    pairs.append((uf_D.find_root(i), uf_T.find_root(i)))

pairs_count = {}

for p in pairs:

    if not p in pairs_count:

        pairs_count[p] = 1

    else:

        pairs_count[p] += 1

res = [0] * N

for i in range(N):

    res[i] = pairs_count[pairs[i]]

#print(*(res[i] for i in range(N)))

print((" ".join([str(i) for i in res])))

N, K, L = list(map(int, input().split()))
# print(N,K,L,D,T)
class UnionFind:
    def __init__(self, n: int) -> None:
        self.par = [i for i in range(n)]
        self.rank = [0] * n

    def find(self, x: int) -> int:
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x: int, y: int) -> None:
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    # def same_check(self, x, y):
    #    return self.find(x) == self.find(y)

def uniteOne(num, uf):
    for _ in range(num):
        d0, d1 = list(map(int, input().split()))
        uf.unite(d0 - 1, d1 - 1)

uf_D = UnionFind(N)
uf_T = UnionFind(N)
uniteOne(K, uf_D)
uniteOne(L, uf_T)
from collections import Counter

keys = []
counts = Counter()
for i in range(N):
    key = uf_D.find(i), uf_T.find(i)
    keys.append(key)
    counts[key] += 1
print((*(counts[key] for key in keys)))

N, K, L = list(map(int, input().split()))
# print(N,K,L,D,T)
class UnionFind:
    def __init__(self, n: int) -> None:
        # マイナスならルートでその深さを表す。プラスならルートのノードを指す。
        self.nodes = [-1] * n

    def find_root(self, x: int) -> int:
        if self.nodes[x] < 0:
            return x
        else:
            self.nodes[x] = self.find_root(self.nodes[x])
            return self.nodes[x]

    def unite(self, x: int, y: int) -> None:
        x, y = self.find_root(x), self.find_root(y)
        # 浅い方につなぐ
        if x != y:
            if x < y:
                self.nodes[y] += self.nodes[x]
                self.nodes[x] = y
            else:
                self.nodes[x] += self.nodes[y]
                self.nodes[y] = x

    # 同じ集合に属するか判定
    # def same_check(self, x, y):
    #    return self.find(x) == self.find(y)

def uniteOne(num, uf):
    for _ in range(num):
        d0, d1 = list(map(int, input().split()))
        uf.unite(d0 - 1, d1 - 1)

uf_D = UnionFind(N)
uf_T = UnionFind(N)
uniteOne(K, uf_D)
uniteOne(L, uf_T)
pairs = []
for i in range(N):
    pairs.append((uf_D.find_root(i), uf_T.find_root(i)))
pairs_count = {}
for p in pairs:
    if not p in pairs_count:
        pairs_count[p] = 1
    else:
        pairs_count[p] += 1
res = [0] * N
for i in range(N):
    res[i] = pairs_count[pairs[i]]
# print(*(res[i] for i in range(N)))
print((" ".join([str(i) for i in res])))

-        self.par = [i for i in range(n)]

+        # マイナスならルートでその深さを表す。プラスならルートのノードを指す。

+    def find_root(self, x: int) -> int:

-            self.par[x] = self.find(self.par[x])

+            self.nodes[x] = self.find_root(self.nodes[x])

-        if self.rank[x] < self.rank[y]:

-            if self.rank[x] == self.rank[y]:

+        x, y = self.find_root(x), self.find_root(y)

+        # 浅い方につなぐ

+                self.nodes[y] += self.nodes[x]

+                self.nodes[x] += self.nodes[y]

-print((*(counts[key] for key in keys)))

+    pairs.append((uf_D.find_root(i), uf_T.find_root(i)))

+print((" ".join([str(i) for i in res])))


Input:
import sys

sys.setrecursionlimit(2*10**5)

def dfs(v, graph, memo):

    if memo[v] != -1:

        return memo[v]

    ret = 0

    for c in graph[v]:

        ret = max(ret, dfs(c, graph, memo) + 1)

    memo[v] = ret

    return ret

def main():

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

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

    for _ in range(M):

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

        x, y = x - 1, y - 1

        graph[x].append(y)

    memo = [-1] * N

    ans = 0

    for i in range(N):

        ans = max(ans, dfs(i, graph, memo))

    print(ans)

if __name__ == '__main__':

    main()

import numpy as np

from scipy.sparse import csr_matrix

from scipy.sparse.csgraph import connected_components

def create_graph(V: int, edges: np.array, dtype=None):

    """csr_matrix を作成する

    もし精度が足りない場合は dtype=object にする。

    """

    return csr_matrix((edges[:, 2], (edges[:, 0], edges[:, 1])),

                      shape=(V, V), dtype=dtype)

def main() -> None:

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

    edges = []

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

    for _ in range(M):

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

        edges.append([x-1, y-1, 1])

        adj_list[x-1].append(y-1)

    graph = create_graph(N, np.asarray(edges))

    _, labels = connected_components(

        csgraph=graph, directed=True,

        connection="strong", return_labels=True)

    order = [(x, i) for i, x in enumerate(labels)]

    order.sort(reverse=True)

    dp = [0] * N

    for _, i in order:

        for v in adj_list[i]:

            dp[v] = max(dp[v], dp[i] + 1)

    print((max(dp)))

if __name__ == '__main__':

    main()

import sys

sys.setrecursionlimit(2 * 10**5)

def dfs(v, graph, memo):
    if memo[v] != -1:
        return memo[v]
    ret = 0
    for c in graph[v]:
        ret = max(ret, dfs(c, graph, memo) + 1)
    memo[v] = ret
    return ret

def main():
    N, M = list(map(int, input().split()))
    graph = [[] for _ in range(N)]
    for _ in range(M):
        x, y = list(map(int, input().split()))
        x, y = x - 1, y - 1
        graph[x].append(y)
    memo = [-1] * N
    ans = 0
    for i in range(N):
        ans = max(ans, dfs(i, graph, memo))
    print(ans)

if __name__ == "__main__":
    main()

import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components

def create_graph(V: int, edges: np.array, dtype=None):
    """csr_matrix を作成する
    もし精度が足りない場合は dtype=object にする。
    """
    return csr_matrix(
        (edges[:, 2], (edges[:, 0], edges[:, 1])), shape=(V, V), dtype=dtype
    )

def main() -> None:
    N, M = list(map(int, input().split()))
    edges = []
    adj_list = [[] for _ in range(N)]
    for _ in range(M):
        x, y = list(map(int, input().split()))
        edges.append([x - 1, y - 1, 1])
        adj_list[x - 1].append(y - 1)
    graph = create_graph(N, np.asarray(edges))
    _, labels = connected_components(
        csgraph=graph, directed=True, connection="strong", return_labels=True
    )
    order = [(x, i) for i, x in enumerate(labels)]
    order.sort(reverse=True)
    dp = [0] * N
    for _, i in order:
        for v in adj_list[i]:
            dp[v] = max(dp[v], dp[i] + 1)
    print((max(dp)))

if __name__ == "__main__":
    main()

+from scipy.sparse.csgraph import connected_components

-        ret = max(ret, dfs(c, graph, memo) + 1)

+def create_graph(V: int, edges: np.array, dtype=None):

+    もし精度が足りない場合は dtype=object にする。

+        (edges[:, 2], (edges[:, 0], edges[:, 1])), shape=(V, V), dtype=dtype

-        ans = max(ans, dfs(i, graph, memo))

+        edges.append([x - 1, y - 1, 1])

+    graph = create_graph(N, np.asarray(edges))

+        csgraph=graph, directed=True, connection="strong", return_labels=True

+    order = [(x, i) for i, x in enumerate(labels)]


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

Ss = eval(input())

def isOK(k):

    strAs = ['' for _ in range(N)]

    strBs = ['' for _ in range(N)]

    for L in range(N-k+1):

        R = L+k-1

        ss = Ss[L:R+1]

        strAs[R] = ss

        strBs[L] = ss

    strCands = set()

    for iEn in range(N-1):

        if strAs[iEn] != '':

            strCands.add(strAs[iEn])

        if strBs[iEn+1] != '' and strBs[iEn+1] in strCands:

            return True

    return False

ng, ok = N//2 + 1, 0

while abs(ok-ng) > 1:

    mid = (ng+ok) // 2

    if isOK(mid):

        ok = mid

    else:

        ng = mid

print(ok)

N = int(eval(input()))

Ss = eval(input())

BASE = 10**9 + 7

MOD = 2**61 - 1

def genRollingHash_AllRight(Ss, lenInit, BASE, MOD):

    As = [ord(S) for S in Ss]

    hashS = 0

    for A in As[:lenInit]:

        hashS = (hashS*BASE + A) % MOD

    yield hashS

    powB_L = pow(BASE, lenInit, MOD)

    for Aadd, Asub in zip(As[lenInit:], As[:len(As)-lenInit]):

        hashS = (hashS*BASE + Aadd - Asub*powB_L) % MOD

        yield hashS

def isOK(k):

    hashSs = list(genRollingHash_AllRight(Ss, k, BASE, MOD))

    setHashS = set()

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

        setHashS.add(hashSs[i-k])

        if hashSs[i] in setHashS:

            return True

    return False

ng, ok = N//2 + 1, 0

while abs(ok-ng) > 1:

    mid = (ng+ok) // 2

    if isOK(mid):

        ok = mid

    else:

        ng = mid

print(ok)

N = int(eval(input()))
Ss = eval(input())

def isOK(k):
    strAs = ["" for _ in range(N)]
    strBs = ["" for _ in range(N)]
    for L in range(N - k + 1):
        R = L + k - 1
        ss = Ss[L : R + 1]
        strAs[R] = ss
        strBs[L] = ss
    strCands = set()
    for iEn in range(N - 1):
        if strAs[iEn] != "":
            strCands.add(strAs[iEn])
        if strBs[iEn + 1] != "" and strBs[iEn + 1] in strCands:
            return True
    return False

ng, ok = N // 2 + 1, 0
while abs(ok - ng) > 1:
    mid = (ng + ok) // 2
    if isOK(mid):
        ok = mid
    else:
        ng = mid
print(ok)

N = int(eval(input()))
Ss = eval(input())
BASE = 10**9 + 7
MOD = 2**61 - 1

def genRollingHash_AllRight(Ss, lenInit, BASE, MOD):
    As = [ord(S) for S in Ss]
    hashS = 0
    for A in As[:lenInit]:
        hashS = (hashS * BASE + A) % MOD
    yield hashS
    powB_L = pow(BASE, lenInit, MOD)
    for Aadd, Asub in zip(As[lenInit:], As[: len(As) - lenInit]):
        hashS = (hashS * BASE + Aadd - Asub * powB_L) % MOD
        yield hashS

def isOK(k):
    hashSs = list(genRollingHash_AllRight(Ss, k, BASE, MOD))
    setHashS = set()
    for i in range(k, N - k + 1):
        setHashS.add(hashSs[i - k])
        if hashSs[i] in setHashS:
            return True
    return False

ng, ok = N // 2 + 1, 0
while abs(ok - ng) > 1:
    mid = (ng + ok) // 2
    if isOK(mid):
        ok = mid
    else:
        ng = mid
print(ok)

+def genRollingHash_AllRight(Ss, lenInit, BASE, MOD):

+        hashS = (hashS * BASE + A) % MOD

+    for Aadd, Asub in zip(As[lenInit:], As[: len(As) - lenInit]):

+        hashS = (hashS * BASE + Aadd - Asub * powB_L) % MOD

-        if strBs[iEn + 1] != "" and strBs[iEn + 1] in strCands:

+    hashSs = list(genRollingHash_AllRight(Ss, k, BASE, MOD))


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

S = eval(input())

answer = 0

for i in range(N-2):

  if S[i:i+3] == "ABC":

    answer += 1

print(answer)

N = int(eval(input()))

S = eval(input())

answer = 0

for i in range(N):

  if i + 3 > N:

    break

  if S[i: i + 3] == "ABC":

    answer += 1

print(answer)

N = int(eval(input()))
S = eval(input())
answer = 0
for i in range(N - 2):
    if S[i : i + 3] == "ABC":
        answer += 1
print(answer)

N = int(eval(input()))
S = eval(input())
answer = 0
for i in range(N):
    if i + 3 > N:
        break
    if S[i : i + 3] == "ABC":
        answer += 1
print(answer)

-for i in range(N - 2):
+for i in range(N):
+    if i + 3 > N:
+        break


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

"""

Created on Mon Sep 28 02:20:36 2020

@author: liang

"""

S = eval(input())

T = eval(input())

S = S[::-1]

T = T[::-1]

res = list()

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

    flag = True

    for j in range(len(T)):

        if S[i+j] == "?" or S[i+j] == T[j]:

            continue

        else:

            flag = False

    if flag == True:

        ans = ""

        for k in range(len(S)):

            if i <= k <= i + len(T)-1:

                #print(T[k-i])

                ans += T[k-i]

            elif S[k] != "?":

                #print("B")

                ans += S[k]

            else:

                #print("C")

                ans += "a"

        ans = ans[::-1]

        res.append(ans)

if res:

    res.sort()

    print((res[0]))

else:

    print("UNRESTORABLE")

#print(S)

#print(T)

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

"""

Created on Mon Sep 28 02:20:36 2020

@author: liang

"""

S = eval(input())

T = eval(input())

S = S[::-1]

T = T[::-1]

res = list()

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

    flag = True

    for j in range(len(T)):

        if S[i+j] == "?" or S[i+j] == T[j]:

            continue

        else:

            flag = False

    if flag == True:

        ans = ""

        for k in range(len(S)):

            if i <= k <= i + len(T)-1:

                #print(T[k-i])

                ans += T[k-i]

            elif S[k] != "?":

                #print("B")

                ans += S[k]

            else:

                #print("C")

                ans += "a"

        ans = ans[::-1]

        print(ans)

        break

        #res.append(ans)

else:

    print("UNRESTORABLE")

"""

if res:

    res.sort()

    print(res[0])

else:

    print("UNRESTORABLE")

"""

#print(S)

#print(T)

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 02:20:36 2020
@author: liang
"""
S = eval(input())
T = eval(input())
S = S[::-1]
T = T[::-1]
res = list()
for i in range(len(S) - len(T) + 1):
    flag = True
    for j in range(len(T)):
        if S[i + j] == "?" or S[i + j] == T[j]:
            continue
        else:
            flag = False
    if flag == True:
        ans = ""
        for k in range(len(S)):
            if i <= k <= i + len(T) - 1:
                # print(T[k-i])
                ans += T[k - i]
            elif S[k] != "?":
                # print("B")
                ans += S[k]
            else:
                # print("C")
                ans += "a"
        ans = ans[::-1]
        res.append(ans)
if res:
    res.sort()
    print((res[0]))
else:
    print("UNRESTORABLE")
# print(S)
# print(T)

# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 02:20:36 2020
@author: liang
"""
S = eval(input())
T = eval(input())
S = S[::-1]
T = T[::-1]
res = list()
for i in range(len(S) - len(T) + 1):
    flag = True
    for j in range(len(T)):
        if S[i + j] == "?" or S[i + j] == T[j]:
            continue
        else:
            flag = False
    if flag == True:
        ans = ""
        for k in range(len(S)):
            if i <= k <= i + len(T) - 1:
                # print(T[k-i])
                ans += T[k - i]
            elif S[k] != "?":
                # print("B")
                ans += S[k]
            else:
                # print("C")
                ans += "a"
        ans = ans[::-1]
        print(ans)
        break
        # res.append(ans)
else:
    print("UNRESTORABLE")
"""
if res:
    res.sort()
    print(res[0])
else:
    print("UNRESTORABLE")
"""
# print(S)
# print(T)

-        res.append(ans)
+        print(ans)
+        break
+        # res.append(ans)
+else:
+    print("UNRESTORABLE")
+"""
-    print((res[0]))
+    print(res[0])
+"""


Input:
N, K = list(map(int, open(0).read().split()))

MAX = 5 * 10 ** 5

MOD = 10 ** 9 + 7

# Factorial

fac = [0] * (MAX + 1)

fac[0] = 1

fac[1] = 1

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

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

# Inverse factorial

finv = [0] * (MAX + 1)

finv[MAX] = pow(fac[MAX], MOD - 2, MOD)

for i in reversed(list(range(1, MAX + 1))):

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

def comb(n, k):

    return fac[n] * finv[n - k] * finv[k]

def rep_perm(n, k):

    return comb(n + k - 1, k)

ans = 0

for k in range(0, min(N, K + 1)):

    ans += comb(N, k) * rep_perm(N - k, k)

    ans %= MOD

print(ans)

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

MAX = 6 * 10 ** 5 + 1

MOD = 10 ** 9 + 7

# Factorial

fac = [0] * (MAX + 1)

fac[0] = 1

fac[1] = 1

# Inverse

inv = [0] * (MAX + 1)

inv[1] = 1

# Inverse factorial

finv = [0] * (MAX + 1)

finv[0] = 1

finv[1] = 1

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

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

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

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

def comb(n, k):

    if n < k or k < 0:

        return 0

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

def comb_rep(n, k):

    return comb(n + k - 1, n - 1)

if K >= N - 1:

    print((comb_rep(N + 1, N - 1)))

else:

    ans = 0

    for i in range(K + 1):

        ans += comb(N, i) * comb_rep(N - i, i) % MOD

        ans %= MOD

    print(ans)

N, K = list(map(int, open(0).read().split()))
MAX = 5 * 10**5
MOD = 10**9 + 7
# Factorial
fac = [0] * (MAX + 1)
fac[0] = 1
fac[1] = 1
for i in range(2, MAX + 1):
    fac[i] = fac[i - 1] * i % MOD
# Inverse factorial
finv = [0] * (MAX + 1)
finv[MAX] = pow(fac[MAX], MOD - 2, MOD)
for i in reversed(list(range(1, MAX + 1))):
    finv[i - 1] = finv[i] * i % MOD

def comb(n, k):
    return fac[n] * finv[n - k] * finv[k]

def rep_perm(n, k):
    return comb(n + k - 1, k)

ans = 0
for k in range(0, min(N, K + 1)):
    ans += comb(N, k) * rep_perm(N - k, k)
    ans %= MOD
print(ans)

N, K = list(map(int, input().split()))
MAX = 6 * 10**5 + 1
MOD = 10**9 + 7
# Factorial
fac = [0] * (MAX + 1)
fac[0] = 1
fac[1] = 1
# Inverse
inv = [0] * (MAX + 1)
inv[1] = 1
# Inverse factorial
finv = [0] * (MAX + 1)
finv[0] = 1
finv[1] = 1
for i in range(2, MAX + 1):
    fac[i] = fac[i - 1] * i % MOD
    inv[i] = MOD - inv[MOD % i] * (MOD // i) % MOD
    finv[i] = finv[i - 1] * inv[i] % MOD

def comb(n, k):
    if n < k or k < 0:
        return 0
    return (fac[n] * finv[k] * finv[n - k]) % MOD

def comb_rep(n, k):
    return comb(n + k - 1, n - 1)

if K >= N - 1:
    print((comb_rep(N + 1, N - 1)))
else:
    ans = 0
    for i in range(K + 1):
        ans += comb(N, i) * comb_rep(N - i, i) % MOD
        ans %= MOD
    print(ans)

-N, K = list(map(int, open(0).read().split()))

-finv[MAX] = pow(fac[MAX], MOD - 2, MOD)

-for i in reversed(list(range(1, MAX + 1))):

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

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

-    return fac[n] * finv[n - k] * finv[k]

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

-    ans += comb(N, k) * rep_perm(N - k, k)

+        ans += comb(N, i) * comb_rep(N - i, i) % MOD


Input:
s = eval(input())

n = len(s)

k = int(eval(input()))

lis = []

b = None

cont = -1

for c in s:

    if c != b:

        if b is not None:

            lis.append(cont)

        b = c

        cont = 1

    else:

        cont += 1

if b is not None:

    lis.append(cont)

# print(lis)

if k == 1 or s[-1] != s[0]:

    print((sum([x // 2 for x in lis]) * k))

else:

    if len(lis) == 1:

        odd = lis[0] // 2

        even = ((lis[0] % 2) + lis[0]) // 2

        # print(odd, even, k // 2)

        print((even * (k // 2) + odd * (k - k // 2)))

    else:

        top = lis[0] // 2

        mid = sum([x // 2 for x in lis[1:-1]])

        bottom = lis[-1] // 2

        joint = (lis[0] + lis[-1]) // 2

        print((top + bottom + joint * (k - 1) + mid * k))

def compress(s):

    z = []

    cont = 1

    for ca, cb in zip(s, s[1:]):

        if ca == cb:

            cont += 1

        else:

            z.append(cont)

            cont = 1

    z.append(cont)

    # print(z)

    return z

def main():

    s = eval(input())

    n = len(s)

    k = int(eval(input()))

    z1 = compress(s)

    if len(z1) == 1:

        # like 'aaa'

        return n * k // 2

    k1 = sum([x // 2 for x in z1])

    if s[0] != s[-1]:

        # like 'ab'

        return k1 * k

    else:

        # like 'aba' / 'abaa'

        z2 = compress(s * 2)

        k2 = sum([x // 2 for x in z2])

        d = k2 - k1

        return k1 + d * (k - 1)

if __name__ == '__main__':

    print((main()))

def compress(s):
    z = []
    cont = 1
    for ca, cb in zip(s, s[1:]):
        if ca == cb:
            cont += 1
        else:
            z.append(cont)
            cont = 1
    z.append(cont)
    # print(z)
    return z

def main():
    s = eval(input())
    n = len(s)
    k = int(eval(input()))
    z1 = compress(s)
    if len(z1) == 1:
        # like 'aaa'
        return n * k // 2
    k1 = sum([x // 2 for x in z1])
    if s[0] != s[-1]:
        # like 'ab'
        return k1 * k
    else:
        # like 'aba' / 'abaa'
        z2 = compress(s * 2)
        k2 = sum([x // 2 for x in z2])
        d = k2 - k1
        return k1 + d * (k - 1)

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

-    print((sum([x // 2 for x in lis]) * k))

-        mid = sum([x // 2 for x in lis[1:-1]])

-        print((top + bottom + joint * (k - 1) + mid * k))


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

FLG = False

for i in range(1,10):

    if 0 < (N/i) < 10 and (N/i).is_integer():

        FLG = True

        break

if FLG:

    print("Yes")

else:

    print("No")

def judge(n):

    for i in range(1,10):

        for j in range(1,10):

            if i*j == n:

                return True

    return False

N = int(eval(input()))

if judge(N):

    print("Yes")

else:

    print("No")

N = int(eval(input()))
FLG = False
for i in range(1, 10):
    if 0 < (N / i) < 10 and (N / i).is_integer():
        FLG = True
        break
if FLG:
    print("Yes")
else:
    print("No")

def judge(n):
    for i in range(1, 10):
        for j in range(1, 10):
            if i * j == n:
                return True
    return False

N = int(eval(input()))
if judge(N):
    print("Yes")
else:
    print("No")

-    if 0 < (N / i) < 10 and (N / i).is_integer():


Input:
import sys

sys.setrecursionlimit(10**7)

def test(array, index, last_position, count, min_count):

    # 除去数が多いパターンは破棄する

    if min_count[0] != -1 and count >= min_count[0]:

        return

    if index + 1 == len(array):

        # print("count:{}".format(count))

        min_count[0] = count if min_count[0] == - \

            1 or count < min_count[0] else min_count[0]

        return

    current = array[index]

    # 前のと手がぶつかる場合は取り除く

    if last_position >= current[2]:

        test(array, index + 1, last_position, count + 1, min_count)

    # 前のとぶつからない場合は取り除かないパターンも

    else:

        test(array, index + 1, index, count, min_count)

N = int(input())

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

for line in array:

    line.append(line[0] - line[1])

    line.append(line[0] + line[1])

array = sorted(array, key=lambda x: x[3])

count = 0

max_r = -float('inf')

for i in range(N):

    current = array[i]

    # print(max_r)

    # print(current[2])

    if current[2] >= max_r:

        # print("残す")

        count += 1

        max_r = current[3]

# test(array, 0, -1, 0, min_count)

print(count)

N = int(eval(input()))

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

for line in array:

    line.append(line[0] - line[1])

    line.append(line[0] + line[1])

array = sorted(array, key=lambda x: x[3])

count = 0

max_r = -float('inf')

for i in range(N):

    current = array[i]

    if current[2] >= max_r:

        count += 1

        max_r = current[3]

print(count)

import sys

sys.setrecursionlimit(10**7)

def test(array, index, last_position, count, min_count):
    # 除去数が多いパターンは破棄する
    if min_count[0] != -1 and count >= min_count[0]:
        return
    if index + 1 == len(array):
        # print("count:{}".format(count))
        min_count[0] = (
            count if min_count[0] == -1 or count < min_count[0] else min_count[0]
        )
        return
    current = array[index]
    # 前のと手がぶつかる場合は取り除く
    if last_position >= current[2]:
        test(array, index + 1, last_position, count + 1, min_count)
    # 前のとぶつからない場合は取り除かないパターンも
    else:
        test(array, index + 1, index, count, min_count)

N = int(input())
array = [list(map(int, input().split())) for i in range(N)]
for line in array:
    line.append(line[0] - line[1])
    line.append(line[0] + line[1])
array = sorted(array, key=lambda x: x[3])
count = 0
max_r = -float("inf")
for i in range(N):
    current = array[i]
    # print(max_r)
    # print(current[2])
    if current[2] >= max_r:
        # print("残す")
        count += 1
        max_r = current[3]
# test(array, 0, -1, 0, min_count)
print(count)

N = int(eval(input()))
array = [list(map(int, input().split())) for i in range(N)]
for line in array:
    line.append(line[0] - line[1])
    line.append(line[0] + line[1])
array = sorted(array, key=lambda x: x[3])
count = 0
max_r = -float("inf")
for i in range(N):
    current = array[i]
    if current[2] >= max_r:
        count += 1
        max_r = current[3]
print(count)

-def test(array, index, last_position, count, min_count):

-    # 除去数が多いパターンは破棄する

-    if min_count[0] != -1 and count >= min_count[0]:

-        # print("count:{}".format(count))

-            count if min_count[0] == -1 or count < min_count[0] else min_count[0]

-    # 前のと手がぶつかる場合は取り除く

-        test(array, index + 1, last_position, count + 1, min_count)

-    # 前のとぶつからない場合は取り除かないパターンも

-        test(array, index + 1, index, count, min_count)


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

if abs(N-M)>1:

    print((0))

    exit()

def cmb(n, r, p):

    if (r < 0) or (n < r):

        return 0

    r = min(r, n - r)

    return fact[n] * factinv[r] * factinv[n-r] % p

p = 10 ** 9 + 7

n = 10 ** 5  # N は必要分だけ用意する

fact = [1, 1]  # fact[n] = (n! mod p) 階乗のmod

factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)

inv = [0, 1]  # factinv 計算用

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

    fact.append((fact[-1] * i) % p)

    inv.append((-inv[p % i] * (p // i)) % p)

    factinv.append((factinv[-1] * inv[-1]) % p)

ans=(fact[N]*fact[M])%p

if N==M:

    ans*=2

    ans%=p

print(ans)

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

if abs(N-M)>1:

    print((0))

    exit()

p = 10 ** 9 + 7

n = 10 ** 5  # N は必要分だけ用意する

fact = [1, 1]  # fact[n] = (n! mod p) 階乗のmod

factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)

inv = [0, 1]  # factinv 計算用

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

    fact.append((fact[-1] * i) % p)

    inv.append((-inv[p % i] * (p // i)) % p)

    factinv.append((factinv[-1] * inv[-1]) % p)

if N==M:

    ans=2*fact[N]*fact[M] % p

else:

    big = max(N, M)

    small = min(N, M)

    ans = fact[N]*fact[M] % p

print(ans)

N, M = list(map(int, input().split()))
if abs(N - M) > 1:
    print((0))
    exit()

def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n - r] % p

p = 10**9 + 7
n = 10**5  # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p) 階乗のmod
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用
for i in range(2, n + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)
ans = (fact[N] * fact[M]) % p
if N == M:
    ans *= 2
    ans %= p
print(ans)

N, M = list(map(int, input().split()))
if abs(N - M) > 1:
    print((0))
    exit()
p = 10**9 + 7
n = 10**5  # N は必要分だけ用意する
fact = [1, 1]  # fact[n] = (n! mod p) 階乗のmod
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用
for i in range(2, n + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)
if N == M:
    ans = 2 * fact[N] * fact[M] % p
else:
    big = max(N, M)
    small = min(N, M)
    ans = fact[N] * fact[M] % p
print(ans)

-    return fact[n] * factinv[r] * factinv[n - r] % p


Input:
import sys

from itertools import accumulate

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

a.sort()

ma = a[-1]

cnt = [0] * (ma + 1)

cur = ma

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

    if a[i] == cur:

        cnt[cur] += 1

    else:

        while True:

            cur -= 1

            cnt[cur] = cnt[cur+1]

            if cur == a[i]:

                cnt[cur] += 1

                break

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

    cnt[i] = cnt[i+1]

def possible(border):

    pair_cnt = 0

    for i in range(n):

        aj = border - a[i]

        if aj < 0:

            aj = 0

        elif aj > ma:

            continue

        pair_cnt += cnt[aj]

    return pair_cnt >= m

def main():

    s = [0] + list(accumulate(a[::-1]))

    lo = 1; hi = a[-1] * 2 + 1

    while lo + 1 < hi:

        border = (lo + hi) // 2

        if possible(border):

            lo = border

        else:

            hi = border

    res = lo

    ans = 0

    minimum = float('inf')

    pair_cnt = 0

    for i in range(n):

        aj = res - a[i]

        if aj < 0:

            aj = 0

        elif aj > ma:

            continue

        c = cnt[aj]

        ans += s[c] + a[i] * c

        pair_cnt += c

        minimum = min(minimum, a[i] + a[-c])

    ans -= minimum * (pair_cnt - m)

    return ans

if __name__ == '__main__':

    ans = main()

    print(ans)

import sys

import numpy as np

I = np.array(sys.stdin.read().split(), dtype=np.int64)

n, m = I[:2]

a = I[2:]

a.sort()

ma = a[-1]

cnt = np.bincount(a, minlength=ma+2)

cnt_not_less_than = np.cumsum(cnt[::-1])[::-1]

right = a[:, None]

def possible(border):

    left = border - right

    left = np.maximum(left, 0)

    left = np.minimum(left, ma+1)

    pair_cnt = np.sum(cnt_not_less_than[left])

    return pair_cnt >= m

def main():

    lo = 1; hi = ma * 2 + 1

    while lo + 1 < hi:

        border = (lo + hi) // 2

        if possible(border):

            lo = border

        else:

            hi = border

    res = lo

    left = res - right

    left = np.maximum(left, 0)

    left = np.minimum(left, ma+1)

    c = cnt_not_less_than[left[left != ma+1]]

    pair_cnt = np.sum(c)

    minimum = np.amin(right[left != ma + 1] + a[-c])

    s = np.cumsum(a[::-1])

    ans = np.sum(s[c-1] + right[left != ma+1] * c) - minimum * (pair_cnt - m)

    return ans

if __name__ == '__main__':

    ans = main()

    print(ans)

import sys
from itertools import accumulate

n, m, *a = list(map(int, sys.stdin.read().split()))
a.sort()
ma = a[-1]
cnt = [0] * (ma + 1)
cur = ma
for i in range(n - 1, -1, -1):
    if a[i] == cur:
        cnt[cur] += 1
    else:
        while True:
            cur -= 1
            cnt[cur] = cnt[cur + 1]
            if cur == a[i]:
                cnt[cur] += 1
                break
for i in range(cur - 1, -1, -1):
    cnt[i] = cnt[i + 1]

def possible(border):
    pair_cnt = 0
    for i in range(n):
        aj = border - a[i]
        if aj < 0:
            aj = 0
        elif aj > ma:
            continue
        pair_cnt += cnt[aj]
    return pair_cnt >= m

def main():
    s = [0] + list(accumulate(a[::-1]))
    lo = 1
    hi = a[-1] * 2 + 1
    while lo + 1 < hi:
        border = (lo + hi) // 2
        if possible(border):
            lo = border
        else:
            hi = border
    res = lo
    ans = 0
    minimum = float("inf")
    pair_cnt = 0
    for i in range(n):
        aj = res - a[i]
        if aj < 0:
            aj = 0
        elif aj > ma:
            continue
        c = cnt[aj]
        ans += s[c] + a[i] * c
        pair_cnt += c
        minimum = min(minimum, a[i] + a[-c])
    ans -= minimum * (pair_cnt - m)
    return ans

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

import sys
import numpy as np

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, m = I[:2]
a = I[2:]
a.sort()
ma = a[-1]
cnt = np.bincount(a, minlength=ma + 2)
cnt_not_less_than = np.cumsum(cnt[::-1])[::-1]
right = a[:, None]

def possible(border):
    left = border - right
    left = np.maximum(left, 0)
    left = np.minimum(left, ma + 1)
    pair_cnt = np.sum(cnt_not_less_than[left])
    return pair_cnt >= m

def main():
    lo = 1
    hi = ma * 2 + 1
    while lo + 1 < hi:
        border = (lo + hi) // 2
        if possible(border):
            lo = border
        else:
            hi = border
    res = lo
    left = res - right
    left = np.maximum(left, 0)
    left = np.minimum(left, ma + 1)
    c = cnt_not_less_than[left[left != ma + 1]]
    pair_cnt = np.sum(c)
    minimum = np.amin(right[left != ma + 1] + a[-c])
    s = np.cumsum(a[::-1])
    ans = np.sum(s[c - 1] + right[left != ma + 1] * c) - minimum * (pair_cnt - m)
    return ans

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

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

+I = np.array(sys.stdin.read().split(), dtype=np.int64)

+    pair_cnt = np.sum(cnt_not_less_than[left])

-    s = [0] + list(accumulate(a[::-1]))

-        minimum = min(minimum, a[i] + a[-c])

+    c = cnt_not_less_than[left[left != ma + 1]]

+    minimum = np.amin(right[left != ma + 1] + a[-c])

+    ans = np.sum(s[c - 1] + right[left != ma + 1] * c) - minimum * (pair_cnt - m)


Input:
# import sys

# input = sys.stdin.readline

def solve():

    N = int(eval(input()))

    brackets_gen = (eval(input()) for _ in range(N))

    grads_positive = list()

    grads_negative = list()

    total = 0

    for brackets in brackets_gen:

        elevation, bottom = 0, 0

        for bk in brackets:

            elevation += 1 if bk == '(' else -1

            bottom = min(bottom, elevation)

        if elevation >= 0:

            grads_positive.append((bottom, elevation))

        elif elevation < 0:

            grads_negative.append((bottom - elevation, -elevation))

        total += elevation

    if total != 0:

        return False

    grads_positive.sort(reverse=True)

    grads_negative.sort(reverse=True)

    def is_good(grads):

        elevation, bottom = 0, 0

        for grad in grads:

            bottom = elevation + grad[0]

            if bottom < 0:

                return False

            elevation += grad[1]

        return True

    if is_good(grads_positive) and is_good(grads_negative):

        return True

    else:

        return False

def main():

    ok = solve()

    if ok:

        print('Yes')

    else:

        print('No')

if __name__ == "__main__":

    main()

import sys

readline = sys.stdin.readline

def solve():

    N = int(eval(input()))

    brackets_gen = (readline().strip() for _ in range(N))

    grads_positive = list()

    grads_negative = list()

    total = 0

    for brackets in brackets_gen:

        elevation, bottom = 0, 0

        for bk in brackets:

            elevation += 1 if bk == '(' else -1

            bottom = min(bottom, elevation)

        if elevation >= 0:

            grads_positive.append((bottom, elevation))

        elif elevation < 0:

            grads_negative.append((bottom - elevation, -elevation))

        total += elevation

    if total != 0:

        return False

    grads_positive.sort(reverse=True)

    grads_negative.sort(reverse=True)

    def is_good(grads):

        elevation, bottom = 0, 0

        for grad in grads:

            bottom = elevation + grad[0]

            if bottom < 0:

                return False

            elevation += grad[1]

        return True

    if is_good(grads_positive) and is_good(grads_negative):

        return True

    else:

        return False

def main():

    ok = solve()

    if ok:

        print('Yes')

    else:

        print('No')

if __name__ == "__main__":

    main()

# import sys
# input = sys.stdin.readline
def solve():
    N = int(eval(input()))
    brackets_gen = (eval(input()) for _ in range(N))
    grads_positive = list()
    grads_negative = list()
    total = 0
    for brackets in brackets_gen:
        elevation, bottom = 0, 0
        for bk in brackets:
            elevation += 1 if bk == "(" else -1
            bottom = min(bottom, elevation)
        if elevation >= 0:
            grads_positive.append((bottom, elevation))
        elif elevation < 0:
            grads_negative.append((bottom - elevation, -elevation))
        total += elevation
    if total != 0:
        return False
    grads_positive.sort(reverse=True)
    grads_negative.sort(reverse=True)

    def is_good(grads):
        elevation, bottom = 0, 0
        for grad in grads:
            bottom = elevation + grad[0]
            if bottom < 0:
                return False
            elevation += grad[1]
        return True

    if is_good(grads_positive) and is_good(grads_negative):
        return True
    else:
        return False

def main():
    ok = solve()
    if ok:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

import sys

readline = sys.stdin.readline

def solve():
    N = int(eval(input()))
    brackets_gen = (readline().strip() for _ in range(N))
    grads_positive = list()
    grads_negative = list()
    total = 0
    for brackets in brackets_gen:
        elevation, bottom = 0, 0
        for bk in brackets:
            elevation += 1 if bk == "(" else -1
            bottom = min(bottom, elevation)
        if elevation >= 0:
            grads_positive.append((bottom, elevation))
        elif elevation < 0:
            grads_negative.append((bottom - elevation, -elevation))
        total += elevation
    if total != 0:
        return False
    grads_positive.sort(reverse=True)
    grads_negative.sort(reverse=True)

    def is_good(grads):
        elevation, bottom = 0, 0
        for grad in grads:
            bottom = elevation + grad[0]
            if bottom < 0:
                return False
            elevation += grad[1]
        return True

    if is_good(grads_positive) and is_good(grads_negative):
        return True
    else:
        return False

def main():
    ok = solve()
    if ok:
        print("Yes")
    else:
        print("No")

if __name__ == "__main__":
    main()

-    brackets_gen = (eval(input()) for _ in range(N))

+    brackets_gen = (readline().strip() for _ in range(N))


Input:
import numpy as np

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

mod = 2019

min_score = 2019

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

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

        if i != j:

            temp = (i%mod)*(j%mod) %mod

            if min_score > temp:

                min_score = temp

            if min_score == 0:

                print(min_score)

                exit()

print(min_score)

import numpy as np

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

mod = 2019

min_score = 2019

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

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

        if i != j:

            temp = (i)*(j) %mod

            if min_score > temp:

                min_score = temp

            if min_score == 0:

                print(min_score)

                exit()

print(min_score)

import numpy as np

a, b = list(map(int, input().split()))
mod = 2019
min_score = 2019
for i in range(a, b + 1):
    for j in range(a, b + 1):
        if i != j:
            temp = (i % mod) * (j % mod) % mod
            if min_score > temp:
                min_score = temp
            if min_score == 0:
                print(min_score)
                exit()
print(min_score)

import numpy as np

a, b = list(map(int, input().split()))
mod = 2019
min_score = 2019
for i in range(a, b + 1):
    for j in range(a, b + 1):
        if i != j:
            temp = (i) * (j) % mod
            if min_score > temp:
                min_score = temp
            if min_score == 0:
                print(min_score)
                exit()
print(min_score)

-            temp = (i % mod) * (j % mod) % mod


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

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

if N==1:

    for i in range(10):

        flg = 0

        for j in range(M):

            s,c = A[j]

            if str(i)[s-1]==str(c):

                continue

            else:

                flg = 1

                break

        if flg==0:

            print(i)

            break

    if flg==1:

        print((-1))

else:

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

        flg = 0

        for j in range(M):

            s,c = A[j]

            if str(i)[s-1]==str(c):

                continue

            else:

                flg = 1

                break

        if flg==0:

            print(i)

            break

    if flg==1:

        print((-1))

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

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

n = -1

for x in range(1000):

    x = str(x)

    if len(x)!=N:continue

    ind = 0

    for i in range(M):

        s,c = A[i]

        if x[int(s)-1]!=str(c):

            ind=1

            break

    if ind==0:

        n = x

        break

print(n)

N, M = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(M)]
if N == 1:
    for i in range(10):
        flg = 0
        for j in range(M):
            s, c = A[j]
            if str(i)[s - 1] == str(c):
                continue
            else:
                flg = 1
                break
        if flg == 0:
            print(i)
            break
    if flg == 1:
        print((-1))
else:
    for i in range(10 ** (N - 1), 10**N):
        flg = 0
        for j in range(M):
            s, c = A[j]
            if str(i)[s - 1] == str(c):
                continue
            else:
                flg = 1
                break
        if flg == 0:
            print(i)
            break
    if flg == 1:
        print((-1))

N, M = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(M)]
n = -1
for x in range(1000):
    x = str(x)
    if len(x) != N:
        continue
    ind = 0
    for i in range(M):
        s, c = A[i]
        if x[int(s) - 1] != str(c):
            ind = 1
            break
    if ind == 0:
        n = x
        break
print(n)


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

if a + b <= k:

    print((0, 0))

else:

    print((0 if a < k else a - k, b + (a - k) if a < k else b))

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

print((0 if a < k else a - k, max(0, b + (a - k)) if a < k else b))

-    print((0 if a < k else a - k, b + (a - k) if a < k else b))

+print((0 if a < k else a - k, max(0, b + (a - k)) if a < k else b))


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

s = eval(input())

if d > c:

    for i in range(a, d-1):

        if s[i-1] == s[i] == "#":

            print("No")

            break

    else:

        print("Yes")

else:

    for i in range(a, c):

        if (s[i-1] == "#") & (s[i] == "#"):

            print("No")

            break

    else:

        for j in range(b-1, d):

            if (s[j-1] == ".") & (s[j] == ".") & (s[j+1] == "."):

                print("Yes")

                break

        else:

            print("No")

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

s = eval(input())

if d > c:

    for i in range(a, d-1):

        if s[i-1] == s[i] == "#":

            print("No")

            break

    else:

        print("Yes")

else:

    for i in range(a, c):

        if s[i-1] == s[i] == "#":

            print("No")

            break

    else:

        for j in range(b-1, d):

            if s[j-1] == s[j] == s[j+1] == ".":

                print("Yes")

                break

        else:

            print("No")

n, a, b, c, d = list(map(int, input().split()))
s = eval(input())
if d > c:
    for i in range(a, d - 1):
        if s[i - 1] == s[i] == "#":
            print("No")
            break
    else:
        print("Yes")
else:
    for i in range(a, c):
        if (s[i - 1] == "#") & (s[i] == "#"):
            print("No")
            break
    else:
        for j in range(b - 1, d):
            if (s[j - 1] == ".") & (s[j] == ".") & (s[j + 1] == "."):
                print("Yes")
                break
        else:
            print("No")

n, a, b, c, d = list(map(int, input().split()))
s = eval(input())
if d > c:
    for i in range(a, d - 1):
        if s[i - 1] == s[i] == "#":
            print("No")
            break
    else:
        print("Yes")
else:
    for i in range(a, c):
        if s[i - 1] == s[i] == "#":
            print("No")
            break
    else:
        for j in range(b - 1, d):
            if s[j - 1] == s[j] == s[j + 1] == ".":
                print("Yes")
                break
        else:
            print("No")


Input:
N, *H = list(map(int, open(0).read().split()))

cnt = 0

for i in range(N - 1):

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

        print('No')

        break

    elif H[i + 1] - H[i] == -1:

        cnt += 1

    elif H[i + 1] - H[i] == 0:

        pass

    else:

        cnt = 0

    if cnt > 1:

        print('No')

        break

else:

    print('Yes')

N = int(eval(input()))

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

cur = 0

flag = True

for i in range(N):

    cur = max(cur, X[i])

    if cur - X[i] > 1:

        flag = False

if flag:

    print("Yes")

else:

    print("No")

N, *H = list(map(int, open(0).read().split()))
cnt = 0
for i in range(N - 1):
    if H[i + 1] - H[i] < -1:
        print("No")
        break
    elif H[i + 1] - H[i] == -1:
        cnt += 1
    elif H[i + 1] - H[i] == 0:
        pass
    else:
        cnt = 0
    if cnt > 1:
        print("No")
        break
else:
    print("Yes")

-N, *H = list(map(int, open(0).read().split()))


Input:
import re

s = eval(input())

t = eval(input())

if len(t) >= len(s) + 1 and re.match(s,t):

    print('Yes')

else:

    print('No')

s = eval(input())

t = input()[:-1]

if s == t:

    print('Yes')

else:

    print('No')

import re

s = eval(input())
t = eval(input())
if len(t) >= len(s) + 1 and re.match(s, t):
    print("Yes")
else:
    print("No")

s = eval(input())
t = input()[:-1]
if s == t:
    print("Yes")
else:
    print("No")

-if len(t) >= len(s) + 1 and re.match(s, t):


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

min_f = 10

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

    if i ** 2 > n:

        break

    if n % i != 0:

        continue

    min_seq = max(len(str(i)), len(str(n // i)))

    if min_seq < min_f:

        min_f = min_seq

print(min_f)

n = int(eval(input()))

n_sqrt = int(n ** 0.5) + 1

ans = float('inf')

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

    if n % i == 0:

        j = int(n // i)

        max_len = max(len(str(i)), len(str(j)))

        ans = min(max_len, ans)

print(ans)

n = int(eval(input()))
min_f = 10
for i in range(1, n + 1):
    if i**2 > n:
        break
    if n % i != 0:
        continue
    min_seq = max(len(str(i)), len(str(n // i)))
    if min_seq < min_f:
        min_f = min_seq
print(min_f)

n = int(eval(input()))
n_sqrt = int(n**0.5) + 1
ans = float("inf")
for i in range(1, n_sqrt + 1):
    if n % i == 0:
        j = int(n // i)
        max_len = max(len(str(i)), len(str(j)))
        ans = min(max_len, ans)
print(ans)

-    min_seq = max(len(str(i)), len(str(n // i)))

+        max_len = max(len(str(i)), len(str(j)))


Input:
import numpy as np

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

ans = 0

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

    j = i

    idx = 0

    while j < K:

        j *= 2

        idx += 1

    ans += 1 / N * np.power(1 / 2 , idx)

print(ans)

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

ans = 0

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

    cnt = 0

    while x < K:

        cnt += 1

        x *= 2

    ans += (1 / N) * (1 / 2) ** cnt

print(ans)

import numpy as np

N, K = list(map(int, input().split()))
ans = 0
for i in range(1, N + 1):
    j = i
    idx = 0
    while j < K:
        j *= 2
        idx += 1
    ans += 1 / N * np.power(1 / 2, idx)
print(ans)

-    ans += 1 / N * np.power(1 / 2, idx)


Input:
#coding:utf-8

import sys

sys.setrecursionlimit(10**6)

write = sys.stdout.write

dbg = lambda *something : print(*something) if DEBUG else 0

DEBUG = False

def main(given = sys.stdin.readline):

    input = lambda : given().rstrip()

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

    II = lambda : int(input())

    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()

    P = input().replace(' ','')

    Q = input().replace(' ','')

    kouho = set(range(1,N+1))

    def kaijo(n):

        ans = 1

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

            ans *= i

        return ans

    numbers = [0] * kaijo(N)

    # print(len(numbers))

    from copy import copy

    def mkp(kouho,i,p):

        if i == N-1:

            numbers.append(p+kouho[0])

            return

        for j in range(len(kouho)):

            kouho2 = copy(kouho)

            kouho2.remove(kouho[j])

            mkp(kouho2,i+1,p+kouho[j])

    mkp(list(map(str,range(1,N+1))),0,'')

    numbers = numbers[kaijo(N):]

    print(abs(numbers.index(P)-numbers.index(Q)))

if __name__ == '__main__':

    main()

#coding:utf-8

import sys

sys.setrecursionlimit(10**6)

write = sys.stdout.write

dbg = lambda *something : print(*something) if DEBUG else 0

DEBUG = False

def main(given = sys.stdin.readline):

    input = lambda : given().rstrip()

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

    II = lambda : int(input())

    XLMIIS = lambda x : [LMIIS() for _ in range(x)]

    N = II()

    P = LMIIS()

    Q = LMIIS()

    from math import factorial

    def index(P):

        candidates = list(range(1,N+1))

        ans = 0

        for i in range(N-1):

            ans += candidates.index(P[i]) * factorial(N-1-i)

            candidates.remove(P[i])

        return ans + 1

    print(abs(index(P)-index(Q)))

if __name__ == '__main__':

    main()

# coding:utf-8
import sys

sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something: print(*something) if DEBUG else 0
DEBUG = False

def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int, input().split()))
    II = lambda: int(input())
    XLMIIS = lambda x: [LMIIS() for _ in range(x)]
    N = II()
    P = input().replace(" ", "")
    Q = input().replace(" ", "")
    kouho = set(range(1, N + 1))

    def kaijo(n):
        ans = 1
        for i in range(1, n + 1):
            ans *= i
        return ans

    numbers = [0] * kaijo(N)
    # print(len(numbers))
    from copy import copy

    def mkp(kouho, i, p):
        if i == N - 1:
            numbers.append(p + kouho[0])
            return
        for j in range(len(kouho)):
            kouho2 = copy(kouho)
            kouho2.remove(kouho[j])
            mkp(kouho2, i + 1, p + kouho[j])

    mkp(list(map(str, range(1, N + 1))), 0, "")
    numbers = numbers[kaijo(N) :]
    print(abs(numbers.index(P) - numbers.index(Q)))

if __name__ == "__main__":
    main()

# coding:utf-8
import sys

sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = lambda *something: print(*something) if DEBUG else 0
DEBUG = False

def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int, input().split()))
    II = lambda: int(input())
    XLMIIS = lambda x: [LMIIS() for _ in range(x)]
    N = II()
    P = LMIIS()
    Q = LMIIS()
    from math import factorial

    def index(P):
        candidates = list(range(1, N + 1))
        ans = 0
        for i in range(N - 1):
            ans += candidates.index(P[i]) * factorial(N - 1 - i)
            candidates.remove(P[i])
        return ans + 1

    print(abs(index(P) - index(Q)))

if __name__ == "__main__":
    main()

+        candidates = list(range(1, N + 1))

+            ans += candidates.index(P[i]) * factorial(N - 1 - i)

-            numbers.append(p + kouho[0])

-            mkp(kouho2, i + 1, p + kouho[j])

-    mkp(list(map(str, range(1, N + 1))), 0, "")

-    print(abs(numbers.index(P) - numbers.index(Q)))


Input:
import sys

readline = sys.stdin.readline

from math import factorial

MOD = 10 ** 9 + 7

def main():

    N, M = list(map(int, readline().rstrip().split()))

    if abs(N-M) > 1:

        ans = 0

    elif N == M:

        ans = (factorial(N) % MOD) * (factorial(M) % MOD) * 2

    else:

        ans = (factorial(N) % MOD) * (factorial(M) % MOD)

    print((ans % MOD))

if __name__ == '__main__':

    main()

import sys

readline = sys.stdin.readline

MOD = 10 ** 9 + 7

def factorial(N, mod=MOD):

    res = 1

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

        res *= i

        res %= mod

    return res

def main():

    N, M = list(map(int, readline().rstrip().split()))

    if abs(N-M) > 1:

        ans = 0

    elif N == M:

        ans = factorial(N) * factorial(M) * 2

    else:

        ans = factorial(N) * factorial(M)

    print((ans % MOD))

if __name__ == '__main__':

    main()

import sys

readline = sys.stdin.readline
from math import factorial

MOD = 10**9 + 7

def main():
    N, M = list(map(int, readline().rstrip().split()))
    if abs(N - M) > 1:
        ans = 0
    elif N == M:
        ans = (factorial(N) % MOD) * (factorial(M) % MOD) * 2
    else:
        ans = (factorial(N) % MOD) * (factorial(M) % MOD)
    print((ans % MOD))

if __name__ == "__main__":
    main()

import sys

readline = sys.stdin.readline
MOD = 10**9 + 7

def factorial(N, mod=MOD):
    res = 1
    for i in range(2, N + 1):
        res *= i
        res %= mod
    return res

def main():
    N, M = list(map(int, readline().rstrip().split()))
    if abs(N - M) > 1:
        ans = 0
    elif N == M:
        ans = factorial(N) * factorial(M) * 2
    else:
        ans = factorial(N) * factorial(M)
    print((ans % MOD))

if __name__ == "__main__":
    main()

-        ans = (factorial(N) % MOD) * (factorial(M) % MOD) * 2

+        ans = factorial(N) * factorial(M) * 2

+        ans = factorial(N) * factorial(M)


Input:
import math

N = int(eval(input()))

print((math.ceil(N/2)))

import math

N = int(eval(input()))
print((math.ceil(N / 2)))

-import math
-N = int(eval(input()))
-print((math.ceil(N / 2)))
+n = int(eval(input()))
+if n % 2 <= 0:
+    print((n // 2))
+elif n % 2 >= 1:
+    print((n // 2 + 1))


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

s=list(eval(input()))

cnt=0

for i in range(1000):

    num=str(i).zfill(3)

    base=s

    for k,j in enumerate(num):

        if j in base:base=base[base.index(j)+1:]

        else:break

        if k==2:cnt +=1

print(cnt)

n=int(eval(input()))

s=eval(input())

cnt=0

for i in range(1000):

    num=str(i).zfill(3)

    x=s.find(num[0])

    y=s.find(num[1],x+1)

    z=s.find(num[2],y+1)

    if x!=-1 and y!=-1 and z!=-1:

        cnt +=1

print(cnt)

n = int(eval(input()))
s = list(eval(input()))
cnt = 0
for i in range(1000):
    num = str(i).zfill(3)
    base = s
    for k, j in enumerate(num):
        if j in base:
            base = base[base.index(j) + 1 :]
        else:
            break
        if k == 2:
            cnt += 1
print(cnt)

n = int(eval(input()))
s = eval(input())
cnt = 0
for i in range(1000):
    num = str(i).zfill(3)
    x = s.find(num[0])
    y = s.find(num[1], x + 1)
    z = s.find(num[2], y + 1)
    if x != -1 and y != -1 and z != -1:
        cnt += 1
print(cnt)

-            base = base[base.index(j) + 1 :]


Input:
def dfs(i,k,s):

    if k == s == 0: return 1

    if i > n or s < i*k+k-1: return 0

    return dfs(i+1,k,s)+dfs(i+1,k-1,s-i)

while 1:

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

    if n == 0: break

    print(dfs(1,k,s))

import itertools

while 1:

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

    if n == 0: break

    print(sum(sum(ele) == s for ele in itertools.combinations(list(range(1,n+1)),k)))

def dfs(i, k, s):
    if k == s == 0:
        return 1
    if i > n or s < i * k + k - 1:
        return 0
    return dfs(i + 1, k, s) + dfs(i + 1, k - 1, s - i)

while 1:
    n, k, s = list(map(int, input().split()))
    if n == 0:
        break
    print(dfs(1, k, s))

import itertools

while 1:
    n, k, s = list(map(int, input().split()))
    if n == 0:
        break
    print(
        sum(sum(ele) == s for ele in itertools.combinations(list(range(1, n + 1)), k))
    )

-    return dfs(i + 1, k, s) + dfs(i + 1, k - 1, s - i)

+        sum(sum(ele) == s for ele in itertools.combinations(list(range(1, n + 1)), k))


Input:
from sys import exit, stdin

input = stdin.readline

import copy

# from collections import deque,Counter

# import numpy as np

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

mod = 10 ** 9 + 7

a, b, c = 1, 1, 2

for i in range(N):

    a = a * 10 % mod

    b = b * 8 % mod

    c = c * 9 % mod

ans = (a + b - c) % mod

print(ans)

from sys import exit, stdin

input = stdin.readline

import copy

# from collections import deque,Counter

# import numpy as np

def pow_mod(a, n, d):

    tmp = 1

    for _ in range(n):

        tmp = (tmp * a) % d

    return tmp

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

mod = 10 ** 9 + 7

ans = (pow_mod(10, N, mod) + pow_mod(8, N, mod) - 2 * pow_mod(9, N, mod)) % mod

print(ans)

from sys import exit, stdin

input = stdin.readline
import copy

# from collections import deque,Counter
# import numpy as np
(N,) = list(map(int, input().split()))
mod = 10**9 + 7
a, b, c = 1, 1, 2
for i in range(N):
    a = a * 10 % mod
    b = b * 8 % mod
    c = c * 9 % mod
ans = (a + b - c) % mod
print(ans)

from sys import exit, stdin

input = stdin.readline
import copy

# from collections import deque,Counter
# import numpy as np
def pow_mod(a, n, d):
    tmp = 1
    for _ in range(n):
        tmp = (tmp * a) % d
    return tmp

(N,) = list(map(int, input().split()))
mod = 10**9 + 7
ans = (pow_mod(10, N, mod) + pow_mod(8, N, mod) - 2 * pow_mod(9, N, mod)) % mod
print(ans)

+ans = (pow_mod(10, N, mod) + pow_mod(8, N, mod) - 2 * pow_mod(9, N, mod)) % mod


Input:
import numpy as np

from numba import njit

i4 = np.int32

i8 = np.int64

u4 = np.uint32

@njit

def get_factorization(n):

    """

    nまでの割り切れる最小の素数を返す。

    """

    sieve_size = (n - 1) // 2

    sieve = np.zeros(sieve_size, u4)

    for i in range(sieve_size):

        if sieve[i] == 0:

            value_at_i = i*2 + 3

            for j in range(i, sieve_size, value_at_i):

                if sieve[j] == 0:

                    sieve[j] = value_at_i

    return sieve

@njit

def solve(A):

    a = np.sort(A)

    p_max = a[-1]

    p = get_factorization(p_max)

    primes_num = 1

    for i in range(p.shape[0]):

        if i*2 + 3 == p[i]:

            primes_num += 1

    a_start = 0

    while a[a_start] == 1:

        a_start += 1

        if a_start == a.shape[0]:

            return 0

    a = a[a_start:]

    if len(a) > primes_num:

        return 1

    check = np.zeros(p_max + 1, u4)

    for d in a:

        if d & 1 == 0:

            check[2] += 1

            d //= 2

            while d & 1 == 0:

                d //= 2

        prev = 2

        while d > 1:

            i = (d - 3) // 2

            f = p[i]

            if f > prev:

                check[f] += 1

                prev = f

            d //= f

    if check.max() > 1:

        return 1

    else:

        return 0

def main(in_file):

    stdin = open(in_file)

    stdin.readline()

    A = np.fromstring(stdin.readline(), u4, sep=' ')

    ans = solve(A)

    if ans:

        g = np.gcd.reduce(A)

        if g > 1:

            ans = 2

        else:

            ans = 1

    p = ['pairwise coprime', 'setwise coprime', 'not coprime']

    print((p[ans]))

if __name__ == '__main__':

    main('/dev/stdin')

import numpy as np

from numba import njit

i4 = np.int32

i8 = np.int64

u4 = np.uint32

@njit

def get_factorization(n):

    """

    nまでの割り切れる最小の素数を返す。

    """

    sieve_size = (n - 1) // 2

    sieve = np.zeros(sieve_size, u4)

    for i in range(sieve_size):

        if sieve[i] == 0:

            value_at_i = i*2 + 3

            for j in range(i, sieve_size, value_at_i):

                if sieve[j] == 0:

                    sieve[j] = value_at_i

    return sieve

@njit('(u4[::-1],)', cache=True)

def solve(A):

    a = np.sort(A)

    p_max = a[-1]

    p = get_factorization(p_max)

    primes_num = 1

    for i in range(p.shape[0]):

        if i*2 + 3 == p[i]:

            primes_num += 1

    a_start = 0

    while a[a_start] == 1:

        a_start += 1

        if a_start == a.shape[0]:

            return 0

    a = a[a_start:]

    if len(a) > primes_num:

        return 1

    check = np.zeros(p_max + 1, u4)

    for d in a:

        if d & 1 == 0:

            check[2] += 1

            d //= 2

            while d & 1 == 0:

                d //= 2

        prev = 2

        while d > 1:

            i = (d - 3) // 2

            f = p[i]

            if f > prev:

                check[f] += 1

                prev = f

            d //= f

    if check.max() > 1:

        return 1

    else:

        return 0

def main(in_file):

    stdin = open(in_file)

    stdin.readline()

    A = np.fromstring(stdin.readline(), u4, sep=' ')

    ans = solve(A)

    if ans:

        g = np.gcd.reduce(A)

        if g > 1:

            ans = 2

        else:

            ans = 1

    p = ['pairwise coprime', 'setwise coprime', 'not coprime']

    print((p[ans]))

if __name__ == '__main__':

    main('/dev/stdin')

import numpy as np
from numba import njit

i4 = np.int32
i8 = np.int64
u4 = np.uint32

@njit
def get_factorization(n):
    """
    nまでの割り切れる最小の素数を返す。
    """
    sieve_size = (n - 1) // 2
    sieve = np.zeros(sieve_size, u4)
    for i in range(sieve_size):
        if sieve[i] == 0:
            value_at_i = i * 2 + 3
            for j in range(i, sieve_size, value_at_i):
                if sieve[j] == 0:
                    sieve[j] = value_at_i
    return sieve

@njit
def solve(A):
    a = np.sort(A)
    p_max = a[-1]
    p = get_factorization(p_max)
    primes_num = 1
    for i in range(p.shape[0]):
        if i * 2 + 3 == p[i]:
            primes_num += 1
    a_start = 0
    while a[a_start] == 1:
        a_start += 1
        if a_start == a.shape[0]:
            return 0
    a = a[a_start:]
    if len(a) > primes_num:
        return 1
    check = np.zeros(p_max + 1, u4)
    for d in a:
        if d & 1 == 0:
            check[2] += 1
            d //= 2
            while d & 1 == 0:
                d //= 2
        prev = 2
        while d > 1:
            i = (d - 3) // 2
            f = p[i]
            if f > prev:
                check[f] += 1
                prev = f
            d //= f
    if check.max() > 1:
        return 1
    else:
        return 0

def main(in_file):
    stdin = open(in_file)
    stdin.readline()
    A = np.fromstring(stdin.readline(), u4, sep=" ")
    ans = solve(A)
    if ans:
        g = np.gcd.reduce(A)
        if g > 1:
            ans = 2
        else:
            ans = 1
    p = ["pairwise coprime", "setwise coprime", "not coprime"]
    print((p[ans]))

if __name__ == "__main__":
    main("/dev/stdin")

import numpy as np
from numba import njit

i4 = np.int32
i8 = np.int64
u4 = np.uint32

@njit
def get_factorization(n):
    """
    nまでの割り切れる最小の素数を返す。
    """
    sieve_size = (n - 1) // 2
    sieve = np.zeros(sieve_size, u4)
    for i in range(sieve_size):
        if sieve[i] == 0:
            value_at_i = i * 2 + 3
            for j in range(i, sieve_size, value_at_i):
                if sieve[j] == 0:
                    sieve[j] = value_at_i
    return sieve

@njit("(u4[::-1],)", cache=True)
def solve(A):
    a = np.sort(A)
    p_max = a[-1]
    p = get_factorization(p_max)
    primes_num = 1
    for i in range(p.shape[0]):
        if i * 2 + 3 == p[i]:
            primes_num += 1
    a_start = 0
    while a[a_start] == 1:
        a_start += 1
        if a_start == a.shape[0]:
            return 0
    a = a[a_start:]
    if len(a) > primes_num:
        return 1
    check = np.zeros(p_max + 1, u4)
    for d in a:
        if d & 1 == 0:
            check[2] += 1
            d //= 2
            while d & 1 == 0:
                d //= 2
        prev = 2
        while d > 1:
            i = (d - 3) // 2
            f = p[i]
            if f > prev:
                check[f] += 1
                prev = f
            d //= f
    if check.max() > 1:
        return 1
    else:
        return 0

def main(in_file):
    stdin = open(in_file)
    stdin.readline()
    A = np.fromstring(stdin.readline(), u4, sep=" ")
    ans = solve(A)
    if ans:
        g = np.gcd.reduce(A)
        if g > 1:
            ans = 2
        else:
            ans = 1
    p = ["pairwise coprime", "setwise coprime", "not coprime"]
    print((p[ans]))

if __name__ == "__main__":
    main("/dev/stdin")


Input:
import numpy

import math

n = int(eval(input()))

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

sum_w = sum(w)

sum_w = sum_w / 2

res = numpy.cumsum(w)

diff = [2.0 * math.fabs(res[i] - sum_w) for i in range(n)]

print((int(min(diff))))

n = int(eval(input()))

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

res = 10 ** 5

for i in range(0, n-1):

  a = abs(sum(w[:i+1]) - sum(w[i+1:]))

  if a < res:

    res = a

print(res)

n = int(eval(input()))
w = list(map(int, input().split()))
res = 10**5
for i in range(0, n - 1):
    a = abs(sum(w[: i + 1]) - sum(w[i + 1 :]))
    if a < res:
        res = a
print(res)

-diff = [2.0 * math.fabs(res[i] - sum_w) for i in range(n)]


Input:
c = [1.1,0.6,0.2,0.0]

r = [0 for i in range(8)]

while 1:

    try:

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

        for i in range(2):

            for j in range(4):

                if e[i] >= c[j]:

                	r[i+2*j] += 1

                	break

    except:

        break

for i in range(0,8,2):

	print(r[i],r[i+1])

from bisect import bisect

ref = [0.2,0.6,1.1]

l,r = [0]*4,[0]*4

while 1:

    try:

        le,re = list(map(float, input().split()))

        l[bisect(ref,le)] += 1

        r[bisect(ref,re)] += 1

    except:

        break

for i in range(1,5):

	print(l[-i],r[-i])

c = [1.1, 0.6, 0.2, 0.0]
r = [0 for i in range(8)]
while 1:
    try:
        e = list(map(float, input().split()))
        for i in range(2):
            for j in range(4):
                if e[i] >= c[j]:
                    r[i + 2 * j] += 1
                    break
    except:
        break
for i in range(0, 8, 2):
    print(r[i], r[i + 1])

from bisect import bisect

ref = [0.2, 0.6, 1.1]
l, r = [0] * 4, [0] * 4
while 1:
    try:
        le, re = list(map(float, input().split()))
        l[bisect(ref, le)] += 1
        r[bisect(ref, re)] += 1
    except:
        break
for i in range(1, 5):
    print(l[-i], r[-i])

-        e = list(map(float, input().split()))

+        le, re = list(map(float, input().split()))


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

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

dict_diffs1 = dict()

dict_diffs2 = dict()

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

  dict_diffs1[i+a[i-1]] = dict_diffs1.get(i+a[i-1], 0) + 1

  dict_diffs2[i-a[i-1]] = dict_diffs2.get(i-a[i-1], 0) + 1

total = 0

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

  total += dict_diffs1.get(j-a[j-1], 0)

  total += dict_diffs2.get(j+a[j-1], 0)

total = total//2

print(total)

n = int(eval(input()))

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

dict_diffs = dict()

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

  dict_diffs[i+a[i-1]] = dict_diffs.get(i+a[i-1], 0) + 1

total = 0

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

  total += dict_diffs.get(j-a[j-1], 0)

print(total)

n = int(eval(input()))
a = list(map(int, input().split()))
dict_diffs1 = dict()
dict_diffs2 = dict()
for i in range(1, n + 1):
    dict_diffs1[i + a[i - 1]] = dict_diffs1.get(i + a[i - 1], 0) + 1
    dict_diffs2[i - a[i - 1]] = dict_diffs2.get(i - a[i - 1], 0) + 1
total = 0
for j in range(1, n + 1):
    total += dict_diffs1.get(j - a[j - 1], 0)
    total += dict_diffs2.get(j + a[j - 1], 0)
total = total // 2
print(total)

n = int(eval(input()))
a = list(map(int, input().split()))
dict_diffs = dict()
for i in range(1, n + 1):
    dict_diffs[i + a[i - 1]] = dict_diffs.get(i + a[i - 1], 0) + 1
total = 0
for j in range(1, n + 1):
    total += dict_diffs.get(j - a[j - 1], 0)
print(total)

-    dict_diffs1[i + a[i - 1]] = dict_diffs1.get(i + a[i - 1], 0) + 1

-    dict_diffs2[i - a[i - 1]] = dict_diffs2.get(i - a[i - 1], 0) + 1

+    dict_diffs[i + a[i - 1]] = dict_diffs.get(i + a[i - 1], 0) + 1

-    total += dict_diffs1.get(j - a[j - 1], 0)

-    total += dict_diffs2.get(j + a[j - 1], 0)

+    total += dict_diffs.get(j - a[j - 1], 0)


Input:
max_num = 10**5+5

eratos_thenes_sieve = [0,0] + [1]*max_num

n = 2 #素数

while n*n <= max_num:

  if eratos_thenes_sieve[n]:#

    for i in range(2*n, max_num, n):

      eratos_thenes_sieve[i] = 0

  n += 1

isLike2017 = [0] * max_num

cumulativeSums = [0]

for i in range(max_num):

  if eratos_thenes_sieve[i] and eratos_thenes_sieve[(i+1)//2]:

    isLike2017[i] = 1

  cumulativeSums.append(cumulativeSums[-1] + isLike2017[i])

q = int(eval(input()))

for i in range(q):

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

  print((cumulativeSums[r+1] - cumulativeSums[l]))

Q = int(eval(input()))

lr = [tuple(map(int, input().split())) for _ in range(Q)]

N = 10**5

is_prime = [True] * (N+1)

is_prime[0] = False

is_prime[1] = False

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

    if is_prime[i]:

        j = 2

        while j * i <= N:

            is_prime[i*j] = False

            j += 1

cum_like2017 = [0] * (N+1)

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

    if is_prime[i] and is_prime[(i+1)//2]:

        cum_like2017[i] = cum_like2017[i-1] + 1

    else:

        cum_like2017[i] = cum_like2017[i-1]

for l, r in lr:

    print((cum_like2017[r] - cum_like2017[l-1]))

max_num = 10**5 + 5
eratos_thenes_sieve = [0, 0] + [1] * max_num
n = 2  # 素数
while n * n <= max_num:
    if eratos_thenes_sieve[n]:  #
        for i in range(2 * n, max_num, n):
            eratos_thenes_sieve[i] = 0
    n += 1
isLike2017 = [0] * max_num
cumulativeSums = [0]
for i in range(max_num):
    if eratos_thenes_sieve[i] and eratos_thenes_sieve[(i + 1) // 2]:
        isLike2017[i] = 1
    cumulativeSums.append(cumulativeSums[-1] + isLike2017[i])
q = int(eval(input()))
for i in range(q):
    l, r = list(map(int, input().split()))
    print((cumulativeSums[r + 1] - cumulativeSums[l]))

Q = int(eval(input()))
lr = [tuple(map(int, input().split())) for _ in range(Q)]
N = 10**5
is_prime = [True] * (N + 1)
is_prime[0] = False
is_prime[1] = False
for i in range(2, N + 1):
    if is_prime[i]:
        j = 2
        while j * i <= N:
            is_prime[i * j] = False
            j += 1
cum_like2017 = [0] * (N + 1)
for i in range(1, N + 1):
    if is_prime[i] and is_prime[(i + 1) // 2]:
        cum_like2017[i] = cum_like2017[i - 1] + 1
    else:
        cum_like2017[i] = cum_like2017[i - 1]
for l, r in lr:
    print((cum_like2017[r] - cum_like2017[l - 1]))

-eratos_thenes_sieve = [0, 0] + [1] * max_num

-        for i in range(2 * n, max_num, n):

-    if eratos_thenes_sieve[i] and eratos_thenes_sieve[(i + 1) // 2]:

-    cumulativeSums.append(cumulativeSums[-1] + isLike2017[i])

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

-    print((cumulativeSums[r + 1] - cumulativeSums[l]))

+lr = [tuple(map(int, input().split())) for _ in range(Q)]

+    if is_prime[i] and is_prime[(i + 1) // 2]:


Input:
from sys import stdin

def main():

    #入力

    readline=stdin.readline

    N=int(readline())

    F=[]

    for i in range(N):

        f=list(map(int,readline().split()))

        F.append(f)

    P=[]

    for i in range(N):

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

        P.append(p)

    max_res=-float("inf")

    for i in range(1<<10):

        if i==0:

            continue

        else:

            output=[]

            for j in range(10):

                if(i>>j)&1:

                    output.append(j)

            oc=[0]*10  #open or close

            for j in output:

                oc[j]=1

            res=0

            for j in range(N):

                c=0

                for k in range(10):

                    if oc[k]==1 and F[j][k]==1:

                        c+=1

                res+=P[j][c]

            max_res=max(res,max_res)

    print(max_res)

if __name__=="__main__":

    main()

from sys import stdin

def main():

    #入力

    readline=stdin.readline

    N=int(readline())

    F=[]

    for i in range(N):

        f=int("".join(readline().strip().split(" ")),2)

        F.append(f)

    P=[]

    for i in range(N):

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

        P.append(p)

    max_res=float("-inf")

    for output in range(1,1<<10):

        res=0

        for j in range(N):

            c=bin(output&F[j]).count("1")

            res+=P[j][c]

        max_res=max(res,max_res)

    print(max_res)

if __name__=="__main__":

    main()

from sys import stdin

def main():
    # 入力
    readline = stdin.readline
    N = int(readline())
    F = []
    for i in range(N):
        f = list(map(int, readline().split()))
        F.append(f)
    P = []
    for i in range(N):
        p = list(map(int, readline().split()))
        P.append(p)
    max_res = -float("inf")
    for i in range(1 << 10):
        if i == 0:
            continue
        else:
            output = []
            for j in range(10):
                if (i >> j) & 1:
                    output.append(j)
            oc = [0] * 10  # open or close
            for j in output:
                oc[j] = 1
            res = 0
            for j in range(N):
                c = 0
                for k in range(10):
                    if oc[k] == 1 and F[j][k] == 1:
                        c += 1
                res += P[j][c]
            max_res = max(res, max_res)
    print(max_res)

if __name__ == "__main__":
    main()

from sys import stdin

def main():
    # 入力
    readline = stdin.readline
    N = int(readline())
    F = []
    for i in range(N):
        f = int("".join(readline().strip().split(" ")), 2)
        F.append(f)
    P = []
    for i in range(N):
        p = list(map(int, readline().split()))
        P.append(p)
    max_res = float("-inf")
    for output in range(1, 1 << 10):
        res = 0
        for j in range(N):
            c = bin(output & F[j]).count("1")
            res += P[j][c]
        max_res = max(res, max_res)
    print(max_res)

if __name__ == "__main__":
    main()

-        f = list(map(int, readline().split()))

+        f = int("".join(readline().strip().split(" ")), 2)

-            oc = [0] * 10  # open or close

-            max_res = max(res, max_res)

+            c = bin(output & F[j]).count("1")


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

List_ans = []

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

    if N % i == 0:

        List_ans.append(i)

x = max(List_ans)

y = N//x

Ans = (x-1) + (y-1)

print(Ans)

N = int(eval(input()))
List_ans = []
for i in range(1, int(N ** (1 / 2)) + 1):
    if N % i == 0:
        List_ans.append(i)
x = max(List_ans)
y = N // x
Ans = (x - 1) + (y - 1)
print(Ans)