N, K = map(int, input().split())
S = input()
ans = 0
for i in range(1, N):
    if S[i] == S[i-1]:
        ans += 1

print(min(N-1, ans+2*K))

def main():
    N, K = map(int, input().split())
    S = list(input())
    base = S[0]
    flag = False
    for i in range(0, N):
        if K == 0:
            break
        if S[i] != base and (not flag):
            flag = True
            S[i] = base
        elif S[i] != base and flag:
            S[i] = base
        elif S[i] == base and flag:
            flag = False
            K -= 1
        else:
            pass

    ans = 0
    for i in range(N-1):
        ans += S[i] == S[i+1]

    print(ans)

if __name__ == "__main__":
    main()

Score : <var>400</var> points

Problem Statement

There are <var>N</var> people standing in a queue from west to east.

Given is a string <var>S</var> of length <var>N</var> representing the directions of the people.
The <var>i</var>-th person from the west is facing west if the <var>i</var>-th character of <var>S</var> is L, and east if that character of <var>S</var> is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between <var>0</var> and <var>K</var> (inclusive):

Operation: Choose integers <var>l</var> and <var>r</var> such that <var>1 \leq l \leq r \leq N</var>, and rotate by <var>180</var> degrees the part of the queue: the <var>l</var>-th, <var>(l+1)</var>-th, <var>...</var>, <var>r</var>-th persons. That is, for each <var>i = 0, 1, ..., r-l</var>, the <var>(l + i)</var>-th person from the west will stand the <var>(r - i)</var>-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

<var>N</var> is an integer satisfying <var>1 \leq N \leq 10^5</var>.

<var>K</var> is an integer satisfying <var>1 \leq K \leq 10^5</var>.

<var>|S| = N</var>

Each character of <var>S</var> is L or R.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>S</var>

Output

Print the maximum possible number of happy people after at most <var>K</var> operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose <var>(l, r) = (2, 5)</var>, we have LLLRLL, where the <var>2</var>-nd, <var>3</var>-rd, and <var>6</var>-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


n, k = [int(i) for i in input().split()]
s = list(input())
c, r, l = 0, 0, 0
if s[0] == 'L':
  l = 1
if s[-1] == 'R':
  r = 1
for i in range(n-1):
  if s[i] == 'R' and s[i+1] == 'L':
    c += 1
if c - k >= 0:
  c -= k
else:
  c = 0
  r = 0
print(n - r - l - 2*c)


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

if n >= 3200:
  print(s)
else:print("red")

def resolve():
    a = int(input())
    s = input()
    print(s if a>=3200 else 'red')
resolve()

Score : <var>100</var> points

Problem Statement

You will be given an integer <var>a</var> and a string <var>s</var> consisting of lowercase English letters as input.

Write a program that prints <var>s</var> if <var>a</var> is not less than <var>3200</var> and prints red if <var>a</var> is less than <var>3200</var>.

Constraints

<var>2800 \leq a < 5000</var>

<var>s</var> is a string of length between <var>1</var> and <var>10</var> (inclusive).

Each character of <var>s</var> is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>a</var>
<var>s</var>

Output

If <var>a</var> is not less than <var>3200</var>, print <var>s</var>; if <var>a</var> is less than <var>3200</var>, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

<var>a = 3200</var> is not less than <var>3200</var>, so we print <var>s =</var> pink.

Sample Input 2

3199
pink

Sample Output 2

red

<var>a = 3199</var> is less than <var>3200</var>, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

<var>a = 4049</var> is not less than <var>3200</var>, so we print <var>s =</var> red.


a = int(input())
s = input()
if a >= 3200:
  print("red")
else:
  print(s)


# for change the recursion limit
import sys
sys.setrecursionlimit(10 ** 6)

# to enable variable use in global
global tree, point

# v : current node, f : parent node
def dfs(v, f):
    for next_v in tree[v]:
        # parents node is already visited
        if next_v == f:
            continue

        point[next_v] += point[v]
        dfs(next_v, v)

n , q = map(int, input().split())
# initalize gloabal variables
tree = [[] for _ in range(n)]
point = [0] * n

for _ in range(n - 1):
    a , b = map(int,input().split())
    tree[b - 1].append(a - 1)
    tree[a - 1].append(b - 1)

for _ in range(q):
    p , x = map(int, input().split())
    point[p - 1] += x

dfs(0, 0)
print(*point)

import sys
sys.setrecursionlimit(10 ** 6)

# to enable variable use in global
global tree, point

# v : current node, f : parent node
def dfs(v, f):
    global tree, point
    for next_v in tree[v]:
        if next_v == f:
            continue

        point[next_v] += point[v]
        dfs(next_v, v)

n , q = map(int, input().split())
tree = [[] for _ in range(n)]
point = [0] * n
for _ in range(n - 1):
    a , b = map(int,input().split())
    tree[b - 1].append(a - 1)
    tree[a - 1].append(b - 1)

for _ in range(q):
    p , x = map(int, input().split())
    point[p - 1] += x

dfs(0, 0)
print(*point)

Score : <var>400</var> points

Problem Statement

Given is a rooted tree with <var>N</var> vertices numbered <var>1</var> to <var>N</var>.
The root is Vertex <var>1</var>, and the <var>i</var>-th edge <var>(1 \leq i \leq N - 1)</var> connects Vertex <var>a_i</var> and <var>b_i</var>.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value <var>0</var>.

Now, the following <var>Q</var> operations will be performed:

Operation <var>j</var> <var>(1 \leq j \leq Q)</var>: Increment by <var>x_j</var> the counter on every vertex contained in the subtree rooted at Vertex <var>p_j</var>.

Find the value of the counter on each vertex after all operations.

Constraints

<var>2 \leq N \leq 2 \times 10^5</var>

<var>1 \leq Q \leq 2 \times 10^5</var>

<var>1 \leq a_i < b_i \leq N</var>

<var>1 \leq p_j \leq N</var>

<var>1 \leq x_j \leq 10^4</var>

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_{N-1}</var> <var>b_{N-1}</var>
<var>p_1</var> <var>x_1</var>
<var>:</var>
<var>p_Q</var> <var>x_Q</var>

Output

Print the values of the counters on Vertex <var>1, 2, \ldots, N</var> after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation <var>1</var>: Increment by <var>10</var> the counter on every vertex contained in the subtree rooted at Vertex <var>2</var>, that is, Vertex <var>2, 3, 4</var>. The values of the counters on Vertex <var>1, 2, 3, 4</var> are now <var>0, 10, 10, 10</var>, respectively.

Operation <var>2</var>: Increment by <var>100</var> the counter on every vertex contained in the subtree rooted at Vertex <var>1</var>, that is, Vertex <var>1, 2, 3, 4</var>. The values of the counters on Vertex <var>1, 2, 3, 4</var> are now <var>100, 110, 110, 110</var>, respectively.

Operation <var>3</var>: Increment by <var>1</var> the counter on every vertex contained in the subtree rooted at Vertex <var>3</var>, that is, Vertex <var>3</var>. The values of the counters on Vertex <var>1, 2, 3, 4</var> are now <var>100, 110, 111, 110</var>, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20


#
# abc138 d
#
import sys
from io import StringIO
import unittest
from collections import deque

class TestClass(unittest.TestCase):
    def assertIO(self, input, output):
        stdout, stdin = sys.stdout, sys.stdin
        sys.stdout, sys.stdin = StringIO(), StringIO(input)
        resolve()
        sys.stdout.seek(0)
        out = sys.stdout.read()[:-1]
        sys.stdout, sys.stdin = stdout, stdin
        self.assertEqual(out, output)

    def test_入力例_1(self):
        input = """4 3
1 2
2 3
2 4
2 10
1 100
3 1"""
        output = """100 110 111 110"""
        self.assertIO(input, output)

    def test_入力例_2(self):
        input = """6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10"""
        output = """20 20 20 20 20 20"""
        self.assertIO(input, output)

def resolve():
    N, Q = map(int, input().split())
    AB = [list(map(int, input().split())) for _ in range(N-1)]
    PX = [list(map(int, input().split())) for _ in range(Q)]

    G = [[i+1, 0] for i in range(N)]
    for ab in AB:
        a, b = ab
        G[a-1][1] += 1
        G[a-1].append(b)

    ans = [0] * N
    for px in PX:
        p, x = px
        ans[p-1] += x

    S = deque()

    F = [False] * N
    S.append(1)
    F[0] = True

    while S:
        p = S.pop()
        if G[p-1][1] == 0:
            continue

        for np in G[p-1][2:]:
            if F[np-1]:
                continue
            S.append(np)
            F[np-1] = True
            ans[np-1] += ans[p-1]

    print(*ans)

if __name__ == "__main__":
    # unittest.main()
    resolve()


a,b = map(int,input().split())
print(max(a+b,a*b,a-b))

A,B=map(int,input().split())
if (A+B)>=(A-B) and (A+B)>=(A*B):
  print(A+B)
elif (A-B)>=(A+B) and (A-B)>=(A*B):
  print(A-B)
elif (A*B)>=(A+B) and (A*B)>=(A-B):
  print(A*B)

Score : <var>100</var> points

Problem Statement

We have two integers: <var>A</var> and <var>B</var>.

Print the largest number among <var>A + B</var>, <var>A - B</var>, and <var>A \times B</var>.

Constraints

All values in input are integers.

<var>-100 \leq A,\ B \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var>

Output

Print the largest number among <var>A + B</var>, <var>A - B</var>, and <var>A \times B</var>.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among <var>A + B = -10</var>, <var>A - B = -16</var>, and <var>A \times B = -39</var> is <var>-10</var>.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among <var>A + B = -32</var>, <var>A - B = 34</var>, and <var>A \times B = -33</var> is <var>34</var>.

Sample Input 3

13 3

Sample Output 3

39

The largest number among <var>A + B = 16</var>, <var>A - B = 10</var>, and <var>A \times B = 39</var> is <var>39</var>.


A,B=map(int,input().split())
if (A+B)>(A-B) and (A+B)>(A*B):
  print(A+B)
elif (A-B)>(A+B) and (A-B)>(A*B):
  print(A-B)
elif (A*B)>(A+B) and (A*B)>(A-B):
  print(A*B)


import sys
import numpy as np
import numba
from numba import njit
i8 = numba.int64

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

MOD = 998_244_353

@njit((i8[:], ), cache=True)
def build(raw_data):
    bit = raw_data.copy()
    for i in range(len(bit)):
        j = i + (i & (-i))
        if j < len(bit):
            bit[j] += bit[i]
    return bit

@njit((i8[:], i8), cache=True)
def get_sum(bit, i):
    s = 0
    while i:
        s += bit[i]
        i -= i & -i
    return s

@njit((i8[:], i8, i8), cache=True)
def add(bit, i, x):
    while i < len(bit):
        bit[i] += x
        i += i & -i

@njit((i8[:], i8), cache=True)
def find_kth_element(bit, k):
    N = len(bit)
    x, sx = 0, 0
    dx = 1
    while 2 * dx < N:
        dx *= 2
    while dx:
        y = x + dx
        if y < N:
            sy = sx + bit[y]
            if sy < k:
                x, sx = y, sy
        dx //= 2
    return x + 1

@njit((i8[:], ), cache=True)
def main(XY):
    X, Y = XY[::2], XY[1::2]
    N = len(Y)
    ind = X.argsort()
    X, Y = X[ind], Y[ind]
    # 座圧
    Y_sort = Y.copy()
    Y_sort.sort()
    Y = np.searchsorted(Y_sort, Y, 'right')
    bit = np.zeros(N + 10, np.int64)

    pow2 = np.ones(N + 10, np.int64)
    for n in range(1, N + 10):
        pow2[n] = 2 * pow2[n - 1] % MOD

    ret = 0
    for i in range(N):
        y = Y[i]
        L = i
        R = N - 1 - i
        LD = get_sum(bit, y)
        add(bit, y, 1)
        LU = L - LD
        D = y - 1
        U = N - 1 - D
        RD = D - LD
        RU = R - RD

        x = pow2[N] - 1
        x -= pow2[L] + pow2[R] + pow2[D] + pow2[U]
        x += pow2[LD] + pow2[LU] + pow2[RD] + pow2[RU]
        ret += x
    return ret % MOD

N = int(readline())
XY = np.array(read().split(), np.int64)

print(main(XY))

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

import numpy as np

MOD = 998244353

N = int(readline())
m = map(int,read().split())
Y = [y for x,y in sorted(zip(m,m))] # Y座標昇順

# 座圧
Y_rank = {y:i for i,y in enumerate(sorted(Y),1)}
Y = [Y_rank[y] for y in Y]

class BIT():
    def __init__(self, max_n):
        self.size = max_n + 1
        self.tree = [0] * self.size

    def get_sum(self,i):
        s = 0
        while i:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i < self.size:
            self.tree[i] += x
            i += i & -i

LD = [0] * N
bit = BIT(N)
for i,y in enumerate(Y):
    LD[i] = bit.get_sum(y)
    bit.add(y,1)

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

x = np.full(N+10,2,np.int64); x[0] = 1
pow2 = cumprod(x,MOD)

LD = np.array(LD,dtype=np.int32)
D = np.array(Y)-1
L = np.arange(N)
R = N-1-L
U = N-1-D
LU = L-LD
RU = U-LU
RD = D-LD

x = pow2[N] - 1 + pow2[LD] + pow2[RD] + pow2[RU] + pow2[LU]
x -= pow2[U] + pow2[D] + pow2[R] + pow2[L]

answer = x.sum() % MOD
print(answer)

Score : <var>600</var> points

Problem Statement

We have a set <var>S</var> of <var>N</var> points in a two-dimensional plane. The coordinates of the <var>i</var>-th point are <var>(x_i, y_i)</var>. The <var>N</var> points have distinct <var>x</var>-coordinates and distinct <var>y</var>-coordinates.

For a non-empty subset <var>T</var> of <var>S</var>, let <var>f(T)</var> be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate axes, that contains all the points in <var>T</var>. More formally, we define <var>f(T)</var> as follows:

<var>f(T) := </var> (the number of integers <var>i</var> <var>(1 \leq i \leq N)</var> such that <var>a \leq x_i \leq b</var> and <var>c \leq y_i \leq d</var>, where <var>a</var>, <var>b</var>, <var>c</var>, and <var>d</var> are the minimum <var>x</var>-coordinate, the maximum <var>x</var>-coordinate, the minimum <var>y</var>-coordinate, and the maximum <var>y</var>-coordinate of the points in <var>T</var>)

Find the sum of <var>f(T)</var> over all non-empty subset <var>T</var> of <var>S</var>. Since it can be enormous, print the sum modulo <var>998244353</var>.

Constraints

<var>1 \leq N \leq 2 \times 10^5</var>

<var>-10^9 \leq x_i, y_i \leq 10^9</var>

<var>x_i \neq x_j (i \neq j)</var>

<var>y_i \neq y_j (i \neq j)</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_N</var> <var>y_N</var>

Output

Print the sum of <var>f(T)</var> over all non-empty subset <var>T</var> of <var>S</var>, modulo <var>998244353</var>.

Sample Input 1

3
-1 3
2 1
3 -2

Sample Output 1

13

Let the first, second, and third points be <var>P_1</var>, <var>P_2</var>, and <var>P_3</var>, respectively. <var>S = \{P_1, P_2, P_3\}</var> has seven non-empty subsets, and <var>f</var> has the following values for each of them:

<var>f(\{P_1\}) = 1</var>

<var>f(\{P_2\}) = 1</var>

<var>f(\{P_3\}) = 1</var>

<var>f(\{P_1, P_2\}) = 2</var>

<var>f(\{P_2, P_3\}) = 2</var>

<var>f(\{P_3, P_1\}) = 3</var>

<var>f(\{P_1, P_2, P_3\}) = 3</var>

The sum of these is <var>13</var>.

Sample Input 2

4
1 4
2 1
3 3
4 2

Sample Output 2

34

Sample Input 3

10
19 -11
-3 -12
5 3
3 -15
8 -14
-9 -20
10 -9
0 2
-7 17
6 -6

Sample Output 3

7222

Be sure to print the sum modulo <var>998244353</var>.


import sys
input = sys.stdin.readline
import numpy as np
def main():
  mod = 998244353
  n = int(input())
  XY = sorted(tuple(map(int, input().split())) for _ in range(n))
  X, Y = zip(*XY)
  L = {y:i+1 for i, y in enumerate(sorted(Y))}
  Y = tuple(L[y] for y in Y)
  BIT = [0]*(n+1)
  def add(i):
    while i<=n:
      BIT[i] += 1
      i += i&-i
  def acc(i):
    res = 0
    while i:
      res += BIT[i]
      i -= i&-i
    return res
  A = [0]*n
  B = [0]*n
  C = [0]*n
  D = [0]*n
  for i, y in enumerate(Y):
    A[i] = acc(y)
    B[i] = i - A[i]
    add(y)
  BIT = [0]*(n+1)
  for i in range(n-1, -1, -1):
    y = Y[i]
    C[i] = acc(y)
    D[i] = n-1-i - C[i]
    add(y)
  T = [1]*n
  for i in range(n-1):
    T[i+1] = T[i]*2%mod
  ans = T[n-1] * n % mod
  A = np.array(tuple(T[a] for a in A), dtype=np.int64)
  B = np.array(tuple(T[b] for b in B), dtype=np.int64)
  C = np.array(tuple(T[c] for c in C), dtype=np.int64)
  D = np.array(tuple(T[d] for d in D), dtype=np.int64)
  temp = (A-1)*B*C*(D-1) + A*(B-1)*(C-1)*D - (A-1)*(B-1)*(C-1)*(D-1)
  temp %= mod
  cnt = temp.sum()%mod
  ans += cnt
  ans %= mod
  print(ans)
if __name__ == "__main__":
  main()


Score : <var>100</var> points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius <var>a</var> is <var>3a^2</var>.

Given an integer <var>r</var>, find the area of a regular dodecagon inscribed in a circle of radius <var>r</var>.

Constraints

<var>1 \leq r \leq 100</var>

<var>r</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>r</var>

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is <var>3 \times 4^2 = 48</var>.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


r = int(input())
print(r ** 2 * (r - 1))


x, a = map(int,input().split())
if (x < a):
  print(0)
else:
  print(10)

#ABC130 A

X,A = map(int,input().split())
if X < A:
    print(0)
else:
    print(10)

Score : <var>100</var> points

Problem Statement

<var>X</var> and <var>A</var> are integers between <var>0</var> and <var>9</var> (inclusive).

If <var>X</var> is less than <var>A</var>, print <var>0</var>; if <var>X</var> is not less than <var>A</var>, print <var>10</var>.

Constraints

<var>0 \leq X, A \leq 9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>A</var>

Output

If <var>X</var> is less than <var>A</var>, print <var>0</var>; if <var>X</var> is not less than <var>A</var>, print <var>10</var>.

Sample Input 1

3 5

Sample Output 1

0

<var>3</var> is less than <var>5</var>, so we should print <var>0</var>.

Sample Input 2

7 5

Sample Output 2

10

<var>7</var> is not less than <var>5</var>, so we should print <var>10</var>.

Sample Input 3

6 6

Sample Output 3

10

<var>6</var> is not less than <var>6</var>, so we should print <var>10</var>.


x,a=map(int,input().split())
if x<a:
  print(10)
else:
  print(0)


MOD=10**9+7
N,A,B,C=map(int,input().split())

def invmod(a):
  return pow(a,MOD-2,MOD)

A,B=100*A*invmod(A+B),100*B*invmod(A+B)

Apow_list=[]
Bpow_list=[]
Apow=Bpow=1
for _ in range(N+1):
  Apow_list.append(Apow)
  Bpow_list.append(Bpow)
  Apow=(Apow*A)%MOD
  Bpow=(Bpow*B)%MOD

# nCr=n!/r!(n-r)!で計算する関数（計算量n*logMOD）…n,rを変えつつ何度も実行する場合
# 各x!および逆元はテーブルで持っておく
fact_list=[1]
fact_inv_list=[1]
for i in range(1,2*N+1):
  fact_mod=(fact_list[-1]*i)%MOD
  fact_list.append(fact_mod)
  fact_inv_list.append(invmod(fact_mod))
def comb_mod_table(n,r):
  if 0<=r<=n:
    return fact_list[n]*fact_inv_list[r]*fact_inv_list[n-r]
  else:
    return 0

answer=0
for M in range(N,2*N):
  bunshi=comb_mod_table(M-1,N-1)
  bunshi*=(Apow_list[N]*Bpow_list[M-N]+Apow_list[M-N]*Bpow_list[N])*M
  bunshi%=MOD
  bumbo=pow(100,M-1,MOD)*(100-C)%MOD
  term=(bunshi*invmod(bumbo))%MOD

  #print(M,term,bunshi,bumbo)
  answer=(answer+term)%MOD

print(answer)

p = 10**9 + 7
N, A, B, C = map(int, input().split())
inv100 = pow(100,p-2,p)
A = A * pow(100-C,p-2,p) % p
B = B * pow(100-C,p-2,p) % p
C = C * inv100 % p

a = [None] * (2*N+1)
inva = [None] * (2*N+1)
a[0] = 1

for i in range(1, 2*N+1):
    a[i] = i * a[i-1] % p

inva[2*N] = pow(a[2*N],p-2,p)
for i in range(2*N):
    inva[2*N-i-1] = inva[2*N-i] * (2*N-i) % p

ans = 0
prevN = pow(A,N,p) * pow(pow(B,N,p),p-2,p) % p

for m in range(N,2*N):
    tmp = (a[m-1] * inva[N-1] % p) * inva[m-N] % p
    tmp *= m
    tmp %= p
    tmp *= ((pow(A,m-N,p) * pow(B,N,p) % p) + (pow(B,m-N,p) * pow(A,N,p) % p)) % p
    tmp %= p
    ans += tmp
    ans %= p
print(ans * pow(1-C,p-2,p)%p)

Score : <var>500</var> points

Problem Statement

Takahashi and Aoki will play a game. They will repeatedly play it until one of them have <var>N</var> wins in total.

When they play the game once, Takahashi wins with probability <var>A</var> %, Aoki wins with probability <var>B</var> %, and the game ends in a draw (that is, nobody wins) with probability <var>C</var> %.
Find the expected number of games that will be played, and print it as follows.

We can represent the expected value as <var>P/Q</var> with coprime integers <var>P</var> and <var>Q</var>.
Print the integer <var>R</var> between <var>0</var> and <var>10^9+6</var> (inclusive) such that <var>R \times Q \equiv P\pmod {10^9+7}</var>.
(Such an integer <var>R</var> always uniquely exists under the constraints of this problem.)

Constraints

<var>1 \leq N \leq 100000</var>

<var>0 \leq A,B,C \leq 100</var>

<var>1 \leq A+B</var>

<var>A+B+C=100</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var> <var>C</var>

Output

Print the expected number of games that will be played, in the manner specified in the statement.

Sample Input 1

1 25 25 50

Sample Output 1

2

Since <var>N=1</var>, they will repeat the game until one of them wins.
The expected number of games played is <var>2</var>.

Sample Input 2

4 50 50 0

Sample Output 2

312500008

<var>C</var> may be <var>0</var>.

Sample Input 3

1 100 0 0

Sample Output 3

1

<var>B</var> may also be <var>0</var>.

Sample Input 4

100000 31 41 28

Sample Output 4

104136146


s = input()

if s.count('x') < 8:
    print('YES')
else:
    print('NO')


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

if a>=13:
  print(b)
elif a>=6 and a<=12:
  print(int(b//2))
else:
  print(0)

a, b = map(int, input().split())
if a <= 5:
    print(0)
elif a <= 12:
    print(b//2)
else:
    print(b)

Score : <var>100</var> points

Problem Statement

Takahashi, who is <var>A</var> years old, is riding a Ferris wheel.

It costs <var>B</var> yen (<var>B</var> is an even number) to ride the Ferris wheel if you are <var>13</var> years old or older, but children between <var>6</var> and <var>12</var> years old (inclusive) can ride it for half the cost, and children who are <var>5</var> years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

<var>0 ≤ A ≤ 100</var>

<var>2 ≤ B ≤ 1000</var>

<var>B</var> is an even number.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var>

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is <var>30</var> years old now, and the cost of the Ferris wheel is <var>100</var> yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is <var>12</var> years old, and the cost of the Ferris wheel is the half of <var>100</var> yen, that is, <var>50</var> yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is <var>0</var> years old, and he can ride the Ferris wheel for free.


A,B = map(int, input().split())
if A >= 13:
	print(B)
elif A > 6:
    print(B // 2)
else:
	print(0)


r,d,x2000 = map(int,input().split())

a = x2000

for x in range(10):
  a = r * a - d
  print(a)

r,d,x=map(int,input().split())
tmp=x
for i in range(10):
    print(r*tmp-d)
    tmp=r*tmp-d

Score : <var>200</var> points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year <var>i</var> be <var>x_i</var> gram. For <var>i≥2000</var>, the following formula holds:

<var>x_{i+1} = rx_i - D</var>

You are given <var>r</var>, <var>D</var> and <var>x_{2000}</var>. Calculate <var>x_{2001}</var>, <var>...</var>, <var>x_{2010}</var> and print them in order.

Constraints

<var>2 ≤ r ≤ 5</var>

<var>1 ≤ D ≤ 100</var>

<var>D < x_{2000} ≤ 200</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>r</var> <var>D</var> <var>x_{2000}</var>

Output

Print <var>10</var> lines. The <var>i</var>-th line (<var>1 ≤ i ≤ 10</var>) should contain <var>x_{2000+i}</var> as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, <var>x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30</var> and <var>x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50</var>.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


r, d, x = map(int, input().split())

for i in range(11):
  x = r * x - d
  print(x)


from networkx.utils import UnionFind
def main():
    n,m=map(int, input().split())
    uf=UnionFind()
    for i in range(n):
        _=uf[i]
    for _ in range(m):
        x,y,z=map(int, input().split())
        uf.union(x-1,y-1)
    print(len(list(uf.to_sets())))

if __name__=='__main__':
    main()

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

par = [-1]*(n)
def find(x):
    if par[x] < 0:
        return x
    else:
        par[x] = find(par[x]) #経路圧縮
        return par[x]
def same(x,y):
    return find(x) == find(y)
def unite(x,y):
    x = find(x)
    y = find(y)
    if x == y:
        return 0
    else:
      if par[x] > par[y]:x,y = y,x
      par[x] += par[y]
      par[y] = x
def size(x):
    return -par[find(x)]

for i in range(m):
  x,y,z = map(int,input().split())
  unite(x-1,y-1)

ans = 0
# print(par)
for i in range(n):
  if par[i] <0:
    ans += 1
print(ans)

Score : <var>500</var> points

Problem Statement

There are <var>N</var> cards placed face down in a row. On each card, an integer <var>1</var> or <var>2</var> is written.

Let <var>A_i</var> be the integer written on the <var>i</var>-th card.

Your objective is to guess <var>A_1, A_2, ..., A_N</var> correctly.

You know the following facts:

For each <var>i = 1, 2, ..., M</var>, the value <var>A_{X_i} + A_{Y_i} + Z_i</var> is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer <var>A_i</var> written on it. The cost of using this magic is <var>1</var>.

What is the minimum cost required to determine all of <var>A_1, A_2, ..., A_N</var>?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

<var>2 \leq N \leq 10^5</var>

<var>1 \leq M \leq 10^5</var>

<var>1 \leq X_i < Y_i \leq N</var>

<var>1 \leq Z_i \leq 100</var>

The pairs <var>(X_i, Y_i)</var> are distinct.

There is no contradiction in input. (That is, there exist integers <var>A_1, A_2, ..., A_N</var> that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>X_1</var> <var>Y_1</var> <var>Z_1</var>
<var>X_2</var> <var>Y_2</var> <var>Z_2</var>
<var>\vdots</var>
<var>X_M</var> <var>Y_M</var> <var>Z_M</var>

Output

Print the minimum total cost required to determine all of <var>A_1, A_2, ..., A_N</var>.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of <var>A_1, A_2, A_3</var> by using the magic for the first and third cards.

Sample Input 2

6 5
1 2 1
2 3 2
1 3 3
4 5 4
5 6 5

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


import heapq

N, M = map(int, input().split())
known = [0] * N
relation = [[] for _ in range(N)]
cost = 0
for _ in range(M):
  X, Y, Z = map(int, input().split())
  relation[X-1].append(Y-1)
  relation[Y-1].append(X-1)

pq = [(-len(relation[n]), n) for n in range(N)]
heapq.heapify(pq)

while len(pq) != 0:
  _, target = heapq.heappop(pq)
  if known[target] == 0:
    cost += 1
  known[target] = 1
  for card in relation[target]:
    known[card] = 1
print(cost)


#!/usr/bin/env python3

#import
import math
#import numpy as np
N = int(input())
A = list(map(int, input().split()))

class SegTree:
    def __init__(self, segfunc, e, v, init_val = None):
        """
        segfunc: function 区間にしたい操作\n
        e: Any 単位元\n
        v: int or List 要素数か格納する配列\n
        init_val: Any 初期値
        """
        self.segfunc = segfunc
        self.e = e
        self.init_val = init_val if init_val != None else e
        if isinstance(v, int):
            v = [self.init_val] * v
        self.n = len(v)
        self.log = (self.n).bit_length()
        self.size = 1 << self.log
        self.tree = [e] * 2 * self.size
        # 1-indexedなのでtree[1:self.size]がN-1要素
        # tree[self.size:self.size + N]が配列
        for i in range(self.n):
            self.tree[self.size + i] = v[i]
        for i in range(self.size - 1, 0, -1):
            self._update(i)

    def set(self, k, x) -> None:
        """
        k番目の値をxに更新\n
        k: index(0-indexed)\n
        x: update value
        """
        k += self.size
        self.tree[k] = x
        for i in range(1, self.log + 1):
            self._update(k >> i)

    def get(self, k):
        """
        a[k]を返す\n
        k: index(0-indexed)
        """
        assert 0 <= k < self.size
        return self.tree[k + self.size]

    def query(self, l, r):
        """
        [l, r)のsegfuncしたものを得る\n
        l: index(0-indexed)\n
        r: index(0-indexed)
        """
        res = self.e
        l += self.size
        r += self.size
        while l < r:
            if l & 1:
                res = self.segfunc(res, self.tree[l])
                l += 1
            if r & 1:
                res = self.segfunc(res, self.tree[r - 1])
            l >>= 1
            r >>= 1
        return res

    def all_query(self):
        """
        全範囲にsegfuncしたものを得る
        """
        return self.tree[1]

    # 二分探索実装、いる？

    def _update(self, k):
        self.tree[k] = self.segfunc(self.tree[k * 2], self.tree[k * 2 + 1])

seg = SegTree(math.gcd, 0, A)

ans = 0

for i in range(N):
    ans = max(ans, math.gcd(seg.query(0, i), seg.query(i + 1, N)))

print(ans)

import math
n = int(input())
a = list(map(int, input().split()))
if n == 1:
    print(10 ** 9)
    exit()
l = [0] * n
r = [0] * n
l[0] = a[0]
r[-1] = a[-1]
for i in range(n-1):
    l[i+1] = math.gcd(a[i+1], l[i])
    r[-i-2] = math.gcd(a[-i-2], r[-i-1])
ans = max(l[-2], r[1])
for i in range(n-2):
    ans = max(ans, math.gcd(l[i], r[i+2]))
print(ans)

Score : <var>300</var> points

Problem Statement

There are <var>N</var> integers, <var>A_1, A_2, ..., A_N</var>, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between <var>1</var> and <var>10^9</var> (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the <var>N</var> integers on the blackboard after your move.

Constraints

All values in input are integers.

<var>2 \leq N \leq 10^5</var>

<var>1 \leq A_i \leq 10^9</var>

Output

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the maximum possible greatest common divisor of the <var>N</var> integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace <var>7</var> with <var>4</var>, the greatest common divisor of the three integers on the blackboard will be <var>2</var>, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


import math
import sys
sys.setrecursionlimit(10**6)
class SegmentTree:

    def __init__(self, size, func=lambda x,y:x+y, default=0):
        """
        size : 配列のサイズ
        func : queryの内容(e.g. 区間和ならf(x, y)=x+y)
        default : 単位元
        """
        self.size = 2**(size-1).bit_length()
        self.default = default
        self.dat = [default for _ in range(self.size*2-1)]
        self.f = func

    def update(self, i, x):
        """
        i番目の値をxに変更する。0-indexedなので注意
        """
        i = i + self.size - 1 #一番下の層の値
        self.dat[i] = x

        while i > 0:
            i = (i-1)>>1
            self.dat[i] = self.f(self.dat[i*2+1], self.dat[i*2+2])

    def query(self, a, b, k=0, L=0, R=None):
        """
        区間[a, b]に関するクエリを処理します。
        例えばi=1,2,3に関して処理したいなら外からquery(1, 3+1)と呼ぶ必要があります。
        """
        if R is None:
            R = self.size

        #区間がかぶっていない場合
        if R <= a or b <= L:
            return self.default

        #区間が完全に収まっている場合
        if a <= L and R <= b:
            return self.dat[k]

        else:
            lres = self.query(a, b, 2*k+1, L, (L+R)>>1)
            rres = self.query(a, b, 2*k+2, (L+R)>>1, R)
            return self.f(lres, rres)

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

segTree = SegmentTree(N, func=lambda x,y:math.gcd(x,y), default=0)
for i in range(N):
    segTree.update(i, A[i])

ans = -1
for i in range(N-1):
    a = segTree.query(0, i)
    b = segTree.query(i+1, N)
    ans = max(ans, math.gcd(a,b))

print(ans)


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

#ans = S.count('#')

cum1=[0]
cnt=0
for i in range(N):
  if S[i]=='#':
    cnt += 1
  cum1.append(cnt)

cum2=[0]
cnt=0
for s in reversed(S):
  if s=='.':
    cnt += 1
  cum2.append(cnt)

cum2 = cum2[::-1]

print(min([cum1[i]+cum2[i] for i in range(N+1)]))

n=int(input())
s=list(input())
bl=0 ; wh=s.count(".")
ans=s.count("#")

for i in range(n):
    ans= min(ans, bl+wh)
    if s[i]=="#":
        bl+=1
    else:
        wh-=1
print(ans)

Score : <var>300</var> points

Problem Statement

There are <var>N</var> stones arranged in a row. Every stone is painted white or black.
A string <var>S</var> represents the color of the stones. The <var>i</var>-th stone from the left is white if the <var>i</var>-th character of <var>S</var> is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

<var>1 \leq N \leq 2\times 10^5</var>

<var>S</var> is a string of length <var>N</var> consisting of . and #.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S</var>

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


import re
N=int(input())
l= input()
print(len(re.findall("#\.",l)))


n = int(input()); x = 0
dp = [[[[0]*4 for q in range(4)] for p in range(4)] for i in range(n-2)]
ng = ["012", "021", "102", "0112", "0132", "0312"]
for p in range(4):
    for q in range(4):
        for r in range(4):
            if str(p)+str(q)+str(r) not in ng:
                dp[0][p][q][r] += 1
for i in range(n-3):
    for p in range(4):
        for q in range(4):
            for r in range(4):
                for s in range(4):
                    if str(p)+str(q)+str(r)+str(s) not in ng and str(q)+str(r)+str(s) not in ng:
                        dp[i+1][q][r][s] += dp[i][p][q][r]
for p in range(4):
    for q in range(4):
        for r in range(4):
            x = (x+dp[-1][p][q][r])%(10**9+7)
print(x)

# 隣接する2文字の入れ替えでAGCとなるパターン(もしくはAGCそのもの)
# AGC
# ACG
# GAC
# AGGC
# ACGC
# ATGC
# AGAC
# AGGC
# AGTC
# 上記を含まない文字列を数える

import sys
readline = sys.stdin.readline

N = int(readline())
DIV = 10 ** 9 + 7

# dp[i][a][b][c] = i文字目について、2つ前がa,1つ前がb,i文字目がdの数で条件を満たすものの数
# 0:"A", 1:"G", 2:"C", 3:"T"
dp = [[[[0] * 4 for b in range(4)] for a in range(4)] for i in range(N)]

C = {0:"A", 1:"G", 2:"C", 3:"T", 4:""}
NG = set(["AGC","ACG","GAC","AGGC","ACGC","AGAC","AGGC","ATGC","AGTC"])

def check_ok(i,j,k,l = 4):
  if (C[i] + C[j] + C[k] + C[l]) in NG:
    return False
  return True

# 3文字目
for i in range(4):
  for j in range(4):
    for k in range(4):
      if check_ok(i,j,k):
        dp[2][i][j][k] += 1

# 4文字目以降を決める
for i in range(2, len(dp) - 1):
  for a in range(4):
    for b in range(4):
      for c in range(4):
        for k in range(4):
          if check_ok(a,b,c,k) and check_ok(b,c,k):
            dp[i + 1][b][c][k] += dp[i][a][b][c]
            dp[i + 1][b][c][k] %= DIV

ans = 0
for a in range(4):
  for b in range(4):
    for c in range(4):
      ans += dp[-1][a][b][c]
      ans %= DIV

print(ans)

Score : <var>400</var> points

Problem Statement

You are given an integer <var>N</var>. Find the number of strings of length <var>N</var> that satisfy the following conditions, modulo <var>10^9+7</var>:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string <var>T</var> is a string obtained by removing zero or more characters from the beginning and the end of <var>T</var>.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

Constraints

<var>3 \leq N \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of strings of length <var>N</var> that satisfy the following conditions, modulo <var>10^9+7</var>.

Sample Input 1

3

Sample Output 1

61

There are <var>4^3 = 64</var> strings of length <var>3</var> that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is <var>64 - 3 = 61</var>.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo <var>10^9+7</var>.


import numpy as np
import re

mod = 10**9 + 7
letters = "ACGT"

# 文字を添え字に
def to_int(s):
    res = 0
    for x in s:
        res <<= 2
        res += letters.index(x)
    return res

# 添え字を文字に
def to_str(x, digit):
    res = ""
    for _ in range(digit):
        res += letters[x&3]
        x >>= 2
    return res[::-1]

# 部分文字列として含んではいけないものを正規表現で判定
def is_ok(s):
    ng = [r"AGC", r"ACG", r"GAC", r"A.GC", r"AG.C"]
    for x in ng:
        if re.search(x, s):
            return False
    return True

# 行列作成　各状態からの各遷移が有効か確かめる
A = [[0]*64 for _ in range(64)]
for i in range(64):
    s = to_str(i, 3)
    for j in range(4):
        t = s + to_str(j, 1)
        if is_ok(t):
            A[i][to_int(t[1:])] = 1
A = np.array(A, dtype = np.int64)

# 行列の二分累乗
def mat_power(A, p, mod):
    res = np.eye(A.shape[0], dtype = np.int64)
    while p:
        if p & 1:
            res = np.dot(res, A) % mod
        A = np.dot(A, A) % mod
        p >>= 1
    return res

# ベクトル作成　TTTのみ立てておく
x = [0]*64
x[63] = 1
x = np.array(x)

N = int(input())
print((np.dot(mat_power(A, N, mod), x) % mod).sum() % mod)


from math import gcd
n = int(input())
a = list(map(int, input().split()))
res = 0
for i in range(n):
    res = gcd(res, a[i])
print(res)

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

import math

def gcd_list(nums):
  gcd = nums[0]
  for i in range(1,len(nums)):
    gcd = math.gcd(gcd,nums[i])
  return gcd

print(gcd_list(A))

Score : <var>300</var> points

Problem Statement

There are <var>N</var> monsters, numbered <var>1, 2, ..., N</var>.

Initially, the health of Monster <var>i</var> is <var>A_i</var>.

Below, a monster with at least <var>1</var> health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

<var>2 \leq N \leq 10^5</var>

<var>1 \leq A_i \leq 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be <var>2</var>, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


n = int(input())
a = list(map(int,input().split()))
g = 0
k = 0
for i in a:
    if i%2 == 0:
        g = 1
    else:
        k = 1
    if g == 1 and k == 1:
        break
if g == 1:
    if k == 1:
        print(1)
    else:
        if len(set(a)) == 1:
            print(a[0])
        else:
            print(2)
else:
    if len(set(a)) == 1:
        print(a[0])
    else:
        print(2)


import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def nCr(com_n, com_r):
    if com_n < com_r: return 0
    return fac[com_n] * ifac[com_r] % md * ifac[com_n - com_r] % md

# combinationの準備
# md>n_maxの条件
md = 998244353
n_max = 4005
fac = [1]
for i in range(1, n_max + 1): fac.append(fac[-1] * i % md)
ifac = [1] * (n_max + 1)
ifac[n_max] = pow(fac[n_max], md - 2, md)
for i in range(n_max - 1, 1, -1): ifac[i] = ifac[i + 1] * (i + 1) % md

def solve():
    dp = [[0] * (n + 1) for _ in range(n + 1)]
    dp[0][0] = 1
    r = b = 0
    for i, c in enumerate(s):
        if c == "0": r += 2
        elif c == "2": b += 2
        else: r, b = r + 1, b + 1
        for j in range(n):
            pre = dp[i][j]
            if pre == 0: continue
            if j + 1 <= r: dp[i + 1][j + 1] += pre
            if i + 1 - j <= b: dp[i + 1][j] += pre
    # p2D(dp)
    ans = 0
    for j in range(n + 1):
        ans += dp[n][j] * nCr(n, r - j)
        ans %= md
    print(ans)

s=SI()
n=len(s)
solve()

S=input()
N=len(S)
mod= 998244353

FACT=[1]
for i in range(1,2*10**5+1):
    FACT.append(FACT[-1]*i%mod)

FACT_INV=[pow(FACT[-1],mod-2,mod)]
for i in range(2*10**5,0,-1):
    FACT_INV.append(FACT_INV[-1]*i%mod)

FACT_INV.reverse()

def Combi(a,b):
    if 0<=b<=a:
        return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod
    else:
        return 0

R=0
B=0

RB=[[0,0]]*N

for i in range(N):
    s=S[i]
    if s=="0":
        R+=2
    elif s=="1":
        R+=1
        B+=1
    else:
        B+=2
    RB[i]=[R,B]

DP=[0]*(R+1)
DP[0]=1

for i in range(N):
    NDP=[0]*(R+1)
    red,blue=RB[i]
    for r in range(R+1):
        if DP[r]==0:
            continue
        if r+1<=red:
            NDP[r+1]+=DP[r]
        if i-r+1<=blue:
            NDP[r]+=DP[r]
    DP=NDP

ANS=0
for r in range(R+1):
    red=R-r
    blue=B-(N-r)

    ANS=ANS+DP[r]*Combi(red+blue,blue)
    ANS%=mod
print(ANS)

Score : <var>900</var> points

Problem Statement

There are <var>N</var> Snukes lining up in a row.
You are given a string <var>S</var> of length <var>N</var>. The <var>i</var>-th Snuke from the front has two red balls if the <var>i</var>-th character in <var>S</var> is 0; one red ball and one blue ball if the <var>i</var>-th character in <var>S</var> is 1; two blue balls if the <var>i</var>-th character in <var>S</var> is 2.

Takahashi has a sequence that is initially empty. Find the number of the possible sequences he may have after repeating the following procedure <var>2N</var> times, modulo <var>998244353</var>:

Each Snuke who has one or more balls simultaneously chooses one of his balls and hand it to the Snuke in front of him, or hand it to Takahashi if he is the first Snuke in the row.

Takahashi receives the ball and put it to the end of his sequence.

Constraints

<var>1 \leq |S| \leq 2000</var>

<var>S</var> consists of 0,1 and 2.

Note that the integer <var>N</var> is not directly given in input; it is given indirectly as the length of the string <var>S</var>.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the number of the possible sequences Takahashi may have after repeating the procedure <var>2N</var> times, modulo <var>998244353</var>.

Sample Input 1

02

Sample Output 1

3

There are three sequences that Takahashi may have: rrbb, rbrb and rbbr, where r and b stand for red and blue balls, respectively.

Sample Input 2

1210

Sample Output 2

55

Sample Input 3

12001021211100201020

Sample Output 3

543589959


s=input()
n=len(s)

DP=[[0 for i in range(2*n+1)] for j in range(2*n+1)]
DP[0][0]=1

ao=0

for i in range(1,2*n+1):
    if i<=n :
        ao+=int(s[i-1])
        aka=min(i,n)*2-ao
    #ao=sum(int(s[t]) for t in range(min(n,i)))
    #aka=min(i,n)*2-ao
    for j in range(0,min(ao+1,i+1)):
        DP[i][j]+=DP[i-1][j-1]
    for j in range(max(0,i-aka),i+1):
        DP[i][j]+=DP[i-1][j]

#print(DP)
print(sum(DP[2*n]))


n, a, b = map(int, input().split())
print(min(a, b), max(0, a + b - n))

Score : <var>100</var> points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the <var>N</var> respondents the following two questions:

Question <var>1</var>: Are you subscribing to Newspaper X?

Question <var>2</var>: Are you subscribing to Newspaper Y?

As the result, <var>A</var> respondents answered "yes" to Question <var>1</var>, and <var>B</var> respondents answered "yes" to Question <var>2</var>.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

<var>1 \leq N \leq 100</var>

<var>0 \leq A \leq N</var>

<var>0 \leq B \leq N</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var>

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the <var>10</var> respondents, <var>3</var> answered they are subscribing to Newspaper X, and <var>5</var> answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most <var>3</var> and at least <var>0</var>.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the <var>10</var> respondents, <var>7</var> answered they are subscribing to Newspaper X, and <var>5</var> answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most <var>5</var> and at least <var>2</var>.

Sample Input 3

100 100 100

Sample Output 3

100 100


n, a, b = map(int, input().split())
if n >= a+b:
    print(min(a, b), 0)
else:
    if a == b:
        print(a, b)
    else:
        print(min(a, b), abs(a-b))


N,M=map(int,input().split())
G1 = [set() for _ in range(N)]
G2 = [set() for _ in range(N)]

for i in range(N-1+M):
  a,b=map(int,input().split())
  G1[a-1].add(b-1)
  G2[b-1].add(a-1)

# https://ikatakos.com/pot/programming_algorithm/graph_theory/topological_sort
inc = [len(G2[i]) for i in range(N)]
S = {i for i, c in enumerate(inc) if c == 0}
L = []

while S:
    n = S.pop()
    L.append(n)
    for m in G1[n]:
        inc[m] -= 1
        if inc[m] == 0:
            S.add(m)

d = [-1]*N
d[L[0]]=0

ans=[0]*N
for v in L[1:]:
  MAX=0
  argmax=-1
  for p in G2[v]:
    if d[p] != -1 and MAX<d[p]+1:
      MAX=d[p]+1
      argmax=p+1
  d[v] = MAX
  ans[v]=argmax

print(*ans)

import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
edges = [[] for i in range(n)]
edges_r = [[] for i in range(n)]
for i in range(n+m-1):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    edges[a].append(b)
    edges_r[b].append(a)

# 根と入次数
s = 0
ks = []
for i,e in enumerate(edges_r):
    if len(e) == 0:
        s = i
    ks.append(len(e))

parents = [-1] * n
INF = 1 << 60
q = deque([s])
while len(q) > 0:
    u = q.popleft()
    for v in edges[u]:
        # 入次数を1減らす
        ks[v] -= 1
        # 0だった時、親が決まる。
        # 親が決まったとき、子を探す
        if ks[v] == 0:
            parents[v] = u
            q.appendleft(v)

for p in parents:
    print(p+1)

Score : <var>500</var> points

Problem Statement

There is a rooted tree (see Notes) with <var>N</var> vertices numbered <var>1</var> to <var>N</var>.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex <var>1</var>.

Takahashi has added <var>M</var> new directed edges to this graph.
Each of these <var>M</var> edges, <var>u \rightarrow v</var>, extends from some vertex <var>u</var> to its descendant <var>v</var>.

You are given the directed graph with <var>N</var> vertices and <var>N-1+M</var> edges after Takahashi added edges.
More specifically, you are given <var>N-1+M</var> pairs of integers, <var>(A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M})</var>, which represent that the <var>i</var>-th edge extends from Vertex <var>A_i</var> to Vertex <var>B_i</var>.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

<var>3 \leq N</var>

<var>1 \leq M</var>

<var>N + M \leq 10^5</var>

<var>1 \leq A_i, B_i \leq N</var>

<var>A_i \neq B_i</var>

If <var>i \neq j</var>, <var>(A_i, B_i) \neq (A_j, B_j)</var>.

The graph in input can be obtained by adding <var>M</var> edges satisfying the condition in the problem statement to a rooted tree with <var>N</var> vertices.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>B_1</var>
<var>:</var>
<var>A_{N-1+M}</var> <var>B_{N-1+M}</var>

Output

Print <var>N</var> lines.
In the <var>i</var>-th line, print 0 if Vertex <var>i</var> is the root of the original tree, and otherwise print the integer representing the parent of Vertex <var>i</var> in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge <var>1 \rightarrow 3</var> to the rooted tree <var>1 \rightarrow 2 \rightarrow 3</var>.

Sample Input 2

6 3
2 1
2 3
4 1
4 2
6 1
2 6
4 6
6 5

Sample Output 2

6
4
2
0
6
2


import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

def main():

    print(0)
    print(1)
    print(2)

if __name__ == '__main__':
    main()


S = input()
s = "keyence"
ans = "NO"

for i in range(len(S)):
  if s == S[:i] + S[len(S)-len(s)+i:]:
    ans = "YES"

print(ans)

s = list(input())
for i in range(7):
    if "".join(s[:i] + s[-(7 - i):]) == "keyence":
        print("YES")
        exit()
print("YES" if "".join(s[:7]) == "keyence" else "NO")

Score : <var>200</var> points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string <var>S</var> consisting of lowercase English letters, determine if <var>S</var> is a KEYENCE string.

Constraints

The length of <var>S</var> is between <var>7</var> and <var>100</var> (inclusive).

<var>S</var> consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


S = input()
s = "keyence"
flag = False
ans = "No"
for i in range(len(S)):
  if s[:i] in S:
    s1 = s[:i]
    s2 = s[i:]
    flag = True

if flag:
  for i in range(len(S)-len(s1)):
    if s1 == S[i:i+len(s1)]:
      if s2 in S[i+len(s1):]:
        ans = "Yes"
        break

print(ans)


import sys
input = sys.stdin.readline

mod = int(1e9+7)

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

A.sort(reverse=True)
B.sort(reverse=True)
if len(set(A)) < N or len(set(B)) < M:
  print(0)
  exit(0)

A.append(0)
B.append(0)
ai,bi = 0,0
ans = 1
for i in range(N*M,0,-1):
  if i == A[ai] and i == B[bi]:
    ai += 1
    bi += 1
  elif i == A[ai]:
    ans *= bi
    ai += 1
  elif i == B[bi]:
    ans *= ai
    bi += 1
  else:
    if min(ai,N) * min(bi,M) - (N*M - i) > 0:
      ans *= (min(ai,N) * min(bi,M) - (N*M - i))
    else:
      #print(0,i,ai,bi)
      print(0)
      exit(0)
  ans %= mod

print(ans)

def permutation(n, k, mod):
    if n < k or k < 0:
        return 0
    s = 1
    for _ in range(k):
        s *= n
        s %= mod
        n -= 1
    return s

n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
mod = pow(10, 9) + 7
a.sort(reverse = True)
b.sort(reverse = True)
a.append(0)
b.append(0)
now = n * m
ok, unknown = 0, 0
i, j = 0, 0
ans = 1 if a[0] == b[0] == now else 0
while not (i == n and j == m):
    unknown = now - max(a[i], b[j])
    now = max(a[i], b[j]) - 1
    ans *= permutation(i * j - ok, unknown, mod)
    ans %= mod
    ok += 1
    if a[i] == b[j]:
        i += 1
        j += 1
    elif a[i] > b[j]:
        i += 1
        ans *= j
        ans %= mod
    else:
        j += 1
        ans *= i
        ans %= mod
    ok += unknown
    unknown = 0
ans *= permutation(now, now, mod)
ans %= mod
print(ans)

Score : <var>500</var> points

Problem Statement

Consider writing each of the integers from <var>1</var> to <var>N \times M</var> in a grid with <var>N</var> rows and <var>M</var> columns, without duplicates.
Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:

The largest among the values in the <var>i</var>-th row <var>(1 \leq i \leq N)</var> is <var>A_i</var>.

The largest among the values in the <var>j</var>-th column <var>(1 \leq j \leq M)</var> is <var>B_j</var>.

For him, find the number of ways to write the numbers under these conditions, modulo <var>10^9 + 7</var>.

Constraints

<var>1 \leq N \leq 1000</var>

<var>1 \leq M \leq 1000</var>

<var>1 \leq A_i \leq N \times M</var>

<var>1 \leq B_j \leq N \times M</var>

<var>A_i</var> and <var>B_j</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_{N}</var>
<var>B_1</var> <var>B_2</var> <var>...</var> <var>B_{M}</var>

Output

Print the number of ways to write the numbers under the conditions, modulo <var>10^9 + 7</var>.

Sample Input 1

2 2
4 3
3 4

Sample Output 1

2

<var>(A_1, A_2) = (4, 3)</var> and <var>(B_1, B_2) = (3, 4)</var>. In this case, there are two ways to write the numbers, as follows:

<var>1</var> in <var>(1, 1)</var>, <var>4</var> in <var>(1, 2)</var>, <var>3</var> in <var>(2, 1)</var> and <var>2</var> in <var>(2, 2)</var>.

<var>2</var> in <var>(1, 1)</var>, <var>4</var> in <var>(1, 2)</var>, <var>3</var> in <var>(2, 1)</var> and <var>1</var> in <var>(2, 2)</var>.

Here, <var>(i, j)</var> denotes the square at the <var>i</var>-th row and the <var>j</var>-th column.

Sample Input 2

3 3
5 9 7
3 6 9

Sample Output 2

0

Since there is no way to write the numbers under the condition, <var>0</var> should be printed.

Sample Input 3

2 2
4 4
4 4

Sample Output 3

0

Sample Input 4

14 13
158 167 181 147 178 151 179 182 176 169 180 129 175 168
181 150 178 179 167 180 176 169 182 177 175 159 173

Sample Output 4

343772227


import sys
input = sys.stdin.readline

mod = int(1e9+7)

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

A.sort(reverse=True)
B.sort(reverse=True)
if len(set(A)) < N or len(set(B)) < M:
  print(0)
  exit(0)

A.append(0)
B.append(0)
ai,bi = 0,0
ans = 1
for i in range(N*M,0,-1):
  if i == A[ai] and i == B[bi]:
    ai += 1
    bi += 1
  elif i == A[ai]:
    ans *= bi
    ai += 1
  elif i == B[bi]:
    ans *= ai
    bi += 1
  else:
    if min(ai,N) * min(bi,M) - (N*M - i) > 0:
      ans *= (min(ai,N) * min(bi,M) - (N*M - i))
    else:
      #print(0,i,ai,bi)
      exit(0)
  ans %= mod

print(ans)


'''
問題を言い換えると
0<=bi<=ai for any iにおいて、sum_i bi = Kとなる通りの数を求めよ

dp[i,j] .. 通りの総数、総和がちょうどjになるとき、:iまでの子供を考慮したとき
dp[i+1,j]=sum_{k=0}^{a_{i}} dp[i,j-k]

これではTLEになりそうなので、累積和で高速に計算する必要がある
'''

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

import numpy as np
from functools import partial
array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

def mina(*argv, sub=1): return list(map(lambda x: x - sub, argv))
# 受け渡されたすべての要素からsubだけ引く.リストを*をつけて展開しておくこと

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

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

MOD = 10**9 + 7

N, K = ints()
A = ints()

from numba import njit

@njit('(i8,i8,i8[:])', cache=True)
def solve(N, K, A):
    dp = np.zeros((N + 1, K + 1), dtype=np.int64)
    dp[0, 0] = 1
    for i in range(N):
        # 前の列の累積和を作りたい
        total = 0
        for j in range(K + 1):
            # ai個でところてんすればいい
            total += dp[i, j]
            total %= MOD
            if j - A[i] - 1 >= 0:
                total -= dp[i, j - A[i] - 1]
            dp[i + 1, j] = total % MOD

    print(dp[N, K])

solve(N, K, A)

import sys
from itertools import accumulate

def main():
  input=sys.stdin.readline
  n,k=map(int,input().split())
  A=list(map(int,input().split()))
  mod=10**9+7
  dp=[0]*(k+1)
  dp[0]=1
  for a in A:
    dp=list(accumulate(dp))
    #print("accumulated",dp)
    for j,d in enumerate(dp[:k-a],start=a+1):
      dp[j]-=d
    dp=[dpi%mod for dpi in dp]
    #print(dp)
  print(dp[k])
"""
def main():
  dp=[[0]*(k+1) for _ in range(n+1)]
  mod=1000000007
  #i人目までに0個配る方法は1通り
  #for i in range(n+1):
  #  dp[i][0]=1
  for i in range(0,n+1):
    for j in range(0,k+1):
      if i==0 and j==0:
        dp[i][j]=1
        break
      if j==0:
        dp[i][j]=1
        continue
      tmp=dp[i - 1][j] + dp[i][j - 1]
      if tmp>=mod:
        tmp%=mod
      dp[i][j]=tmp
      if j-a[i-1]-1>=0:
        tmp=dp[i][j]-dp[i-1][j-a[i-1]-1]
        if tmp>=mod:
          tmp%=mod
        dp[i][j]=tmp
    #print(dp)
  print(dp[n][k])"""
main()

Score : <var>100</var> points

Problem Statement

There are <var>N</var> children, numbered <var>1, 2, \ldots, N</var>.

They have decided to share <var>K</var> candies among themselves.
Here, for each <var>i</var> (<var>1 \leq i \leq N</var>), Child <var>i</var> must receive between <var>0</var> and <var>a_i</var> candies (inclusive).
Also, no candies should be left over.

Find the number of ways for them to share candies, modulo <var>10^9 + 7</var>.
Here, two ways are said to be different when there exists a child who receives a different number of candies.

Constraints

All values in input are integers.

<var>1 \leq N \leq 100</var>

<var>0 \leq K \leq 10^5</var>

<var>0 \leq a_i \leq K</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>a_1</var> <var>a_2</var> <var>\ldots</var> <var>a_N</var>

Output

Print the number of ways for the children to share candies, modulo <var>10^9 + 7</var>.

Sample Input 1

3 4
1 2 3

Sample Output 1

5

There are five ways for the children to share candies, as follows:

<var>(0, 1, 3)</var>

<var>(0, 2, 2)</var>

<var>(1, 0, 3)</var>

<var>(1, 1, 2)</var>

<var>(1, 2, 1)</var>

Here, in each sequence, the <var>i</var>-th element represents the number of candies that Child <var>i</var> receives.

Sample Input 2

1 10
9

Sample Output 2

0

There may be no ways for the children to share candies.

Sample Input 3

2 0
0 0

Sample Output 3

1

There is one way for the children to share candies, as follows:

<var>(0, 0)</var>

Sample Input 4

4 100000
100000 100000 100000 100000

Sample Output 4

665683269

Be sure to print the answer modulo <var>10^9 + 7</var>.


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

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

dpt = [[0] * (K+1) for i in range(N+1)]
for i in range(K+1):
    dpt[0][i] = 1

for i in range(1, N+1):
    for j in range(0, K+1):
        dpt[i][j] += dpt[i-1][j]
        t = j - max_candies[i-1] - 1
        if t >= 0:
            dpt[i][j] -= dpt[i-1][t]
        if j > 0:
            dpt[i][j] += dpt[i][j-1]
        dpt[i][j] = dpt[i][j] % (10**9+7)

print(dpt[N][K]-dpt[N][K-1])


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

import numpy as np
from functools import partial
array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

ra = range
enu = enumerate

def a_int(): return int(read())

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import

from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce

K = np.array(list(map(int, list(input()))))
D = a_int()

'''
ある数xにおいて総和がDの倍数であるかの判定
x[0]+x[1]...+x[n] ≡ 0 (mod D) 各桁の和にMODを取れば良い。つまり桁ごとに処理できる

dp[i,j,k] ... K[:i]以下の整数のうち、k=mod Dとなるような数字の個数。j==1は上位桁が一致している場合の通りの個数。j==0は上位桁が一致しなくなったときの個数。

遷移
for l in range(10):
    dp[i+1,0,(k+l)%D] += dp[i,0,k] #1~9を考慮可能
for l in range(K[i]):
    dp[i+1,0,(k+l)%D] += dp[i,1,k] #1~K[i]-1をつけるとぴったりにならないグループへ行く

dp[i+1,1,(k+K[i])%D] += dp[i,1,k]
'''
# print(K, D)

from numba import njit

@njit('(i8[:],i8)', cache=True)
def solve(K, D):
    N = K.shape[0]
    dp = np.zeros((N + 1, 2, D), dtype=np.int64)
    dp[0, 1, 0] = 1
    for i in range(N):  # 各桁について
        for k in range(D):  # 各あまりについて処理
            for l in range(K[i]):
                # 1~K[i]-1をつけるとぴったりにならないグループへ行く
                dp[i + 1, 0, (k + l) % D] += dp[i, 1, k]
            for l in range(10):  # 各数字について処理
                dp[i + 1, 0, (k + l) % D] += dp[i, 0, k]  # 1~9を考慮可能
                dp[i + 1, 0, (k + l) % D] %= MOD
            # ぴったりグループ
            dp[i + 1, 1, (k + K[i]) % D] += dp[i, 1, k]
            # dp[i + 1, 1, (k + K[i]) % D] %= MOD

    print((dp[-1, :, 0].sum() - 1) % MOD)  # -1は0の分

solve(K, D)

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

import numpy as np
from functools import partial
array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

ra = range
enu = enumerate

def a_int(): return int(read())

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import

K = np.array(list(map(int, list(input()))))
D = a_int()

'''
ある数xにおいて総和がDの倍数であるかの判定
x[0]+x[1]...+x[n] ≡ 0 (mod D) 各桁の和にMODを取れば良い。つまり桁ごとに処理できる

dp[i,j,k] ... K[:i]以下の整数のうち、k=mod Dとなるような数字の個数。j==1は上位桁が一致している場合の通りの個数。j==0は上位桁が一致しなくなったときの個数。

遷移
for l in range(10):
    dp[i+1,0,(k+l)%D] += dp[i,0,k] #1~9を考慮可能
for l in range(K[i]):
    dp[i+1,0,(k+l)%D] += dp[i,1,k] #1~K[i]-1をつけるとぴったりにならないグループへ行く

dp[i+1,1,(k+K[i])%D] += dp[i,1,k]
'''
# print(K, D)

from numba import njit

@njit('(i8[:],i8)', cache=True)
def solve(K, D):
    N = K.shape[0]
    dp = np.zeros((N + 1, 2, D), dtype=np.int64)
    dp[0, 1, 0] = 1
    for i in range(N):  # 各桁について
        for k in range(D):  # 各あまりについて処理
            # for l in range(K[i]):
            #     # 1~K[i]-1をつけるとぴったりにならないグループへ行く
            #     dp[i + 1, 0, (k + l) % D] += dp[i, 1, k]
            # for l in range(10):  # 各数字について処理
            #     dp[i + 1, 0, (k + l) % D] += dp[i, 0, k]  # 1~9を考慮可能
            #     dp[i + 1, 0, (k + l) % D] %= MOD
            for l in range(10):
                m = (k + l) % D
                if l < K[i]:
                    dp[i + 1, 0, m] += dp[i, 0, k] + dp[i, 1, k]
                else:
                    dp[i + 1, 0, m] += dp[i, 0, k]  # 1~9を考慮可能
                dp[i + 1, 0, m] %= MOD

            # ぴったりグループ
            dp[i + 1, 1, (k + K[i]) % D] += dp[i, 1, k]
            # dp[i + 1, 1, (k + K[i]) % D] %= MOD

    print((dp[-1, :, 0].sum() - 1) % MOD)  # -1は0の分

solve(K, D)

Score : <var>100</var> points

Problem Statement

Find the number of integers between <var>1</var> and <var>K</var> (inclusive) satisfying the following condition, modulo <var>10^9 + 7</var>:

The sum of the digits in base ten is a multiple of <var>D</var>.

Constraints

All values in input are integers.

<var>1 \leq K < 10^{10000}</var>

<var>1 \leq D \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>K</var>
<var>D</var>

Output

Print the number of integers satisfying the condition, modulo <var>10^9 + 7</var>.

Sample Input 1

30
4

Sample Output 1

6

Those six integers are: <var>4, 8, 13, 17, 22</var> and <var>26</var>.

Sample Input 2

1000000009
1

Sample Output 2

2

Be sure to print the number modulo <var>10^9 + 7</var>.

Sample Input 3

98765432109876543210
58

Sample Output 3

635270834


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

import numpy as np
from functools import partial
array = partial(np.array, dtype=np.int64)
zeros = partial(np.zeros, dtype=np.int64)
full = partial(np.full, dtype=np.int64)

ra = range
enu = enumerate

def a_int(): return int(read())

MOD = 10**9 + 7
INF = 2**31  # 2147483648 > 10**9
# default import

from collections import defaultdict, Counter, deque
from operator import itemgetter, xor, add
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right
from functools import reduce

K = np.array(list(map(int, list(input()))))
D = a_int()

'''
ある数xにおいて総和がDの倍数であるかの判定
x[0]+x[1]...+x[n] ≡ 0 (mod D) 各桁の和にMODを取れば良い。つまり桁ごとに処理できる

dp[i,j,k] ... K[:i]以下の整数のうち、k=mod Dとなるような数字の個数。j==1は上位桁が一致している場合の通りの個数。j==0は上位桁が一致しなくなったときの個数。

遷移
for l in range(10):
    dp[i+1,0,(k+l)%D] += dp[i,0,k] #1~9を考慮可能
for l in range(K[i]):
    dp[i+1,0,(k+l)%D] += dp[i,1,k] #1~K[i]-1をつけるとぴったりにならないグループへ行く

dp[i+1,1,(k+K[i])%D] += dp[i,1,k]
'''
# print(K, D)

from numba import njit

@njit('(i8[:],i8)', cache=True)
def solve(K, D):
    N = K.shape[0]
    dp = np.zeros((N + 1, 2, D), dtype=np.int64)
    dp[0, 1, 0] = 1
    for i in range(N):  # 各桁について
        for k in range(D):  # 各あまりについて処理
            for l in range(10):  # 各数字について処理
                dp[i + 1, 0, (k + l) % D] += dp[i, 0, k]  # 1~9を考慮可能
                dp[i + 1, 0, (k + l) % D] %= MOD
            for l in range(K[i]):
                # 1~K[i]-1をつけるとぴったりにならないグループへ行く
                dp[i + 1, 0, (k + l) % D] += dp[i, 1, k]
                dp[i + 1, 0, (k + l) % D] %= MOD
            dp[i + 1, 1, (k + K[i]) % D] += dp[i, 1, k]
            dp[i + 1, 1, (k + K[i]) % D] %= MOD

    # print(dp)
    print(dp[-1, :, 0].sum() % MOD - 1)  # -1は0の分

solve(K, D)


from collections import Counter

n = int(input())
l = sorted(list(map(int,input().split())))
d = Counter(l)
ans = 0
for i in range(n-1,-1,-1):
    if d[l[i]] == 0:
        continue
    d[l[i]] -= 1
    x = 2**(l[i].bit_length())
    y = x-l[i]
    if d[y] > 0:
        d[y] -= 1
        ans += 1

print(ans)

from collections import defaultdict
d = defaultdict(int)
n = int(input())
l = sorted(list(map(int,input().split())))
for i in l:
    d[i] += 1

ans = 0
for i in range(n-1,-1,-1):
    if d[l[i]] == 0:
        continue
    x = 2**(l[i].bit_length())
    y = x-l[i]
    if y == l[i]:
        if d[y] >= 2:
            d[y] -= 2
            ans += 1
    else:
        if d[y] > 0:
            d[y] -= 1
            d[l[i]] -= 1
            ans += 1

print(ans)

Score : <var>600</var> points

Problem Statement

Takahashi has <var>N</var> balls with positive integers written on them. The integer written on the <var>i</var>-th ball is <var>A_i</var>.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of <var>2</var>.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of <var>2</var> when it can be written as <var>2^t</var> using some non-negative integer <var>t</var>.

Constraints

<var>1 \leq N \leq 2\times 10^5</var>

<var>1 \leq A_i \leq 10^9</var>

<var>A_i</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of <var>2</var>.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is <var>4</var> by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


import bisect
N=int(input())
A=list(map(int,input().split()))
A=sorted(A)
left,right=0,N-1
cnt=0
D=[1]*N
for i in range(N):
  if D[-1-i]==1:
    D[-1-i]=0
    for j in range(1,16):
      d=2**j
      if A[-1-i]<d:
        e=d
        break
    le=bisect.bisect_left(A,d-A[-1-i])
    ri1=bisect.bisect_right(A,d-A[-1-i])
    ri2=bisect.bisect_right(A,A[-1-i])
    ri=min(ri1,ri2)
    if ri-le>0:
      for k in range(le,ri):
        if D[k]==1:
          D[k]=0
          cnt+=1
print(cnt)


# B AtCoder Beginner Contest 111
N = list(input())
n = int("".join(N))
ck = int(N[0] * 3)
if n - ck <= 0:
    print(int(N[0] * 3))
else:
    print(int(str(int(N[0])+1)*3))
pass

def answer(n: int) -> int:
    q = n // 111
    if n % 111 != 0:
        q += 1

    return 111 * q

def main():
    n = int(input())
    print(answer(n))

if __name__ == '__main__':
    main()

Score : <var>200</var> points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC <var>N</var> (the <var>N</var>-th ABC ever held).
Kurohashi wants to make his debut in some ABC <var>x</var> such that all the digits of <var>x</var> in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

<var>100 \leq N \leq 999</var>

<var>N</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If the earliest ABC where Kurohashi can make his debut is ABC <var>n</var>, print <var>n</var>.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC <var>111</var>, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC <var>112</var>, which means Kurohashi can no longer participate in ABC <var>111</var>.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC <var>222</var>.

Sample Input 3

750

Sample Output 3

777


n = input()
mx = 0
for i in range(3):
    if int(n[i]) > mx:
        mx = int(n[i])
print(str(mx)*3)


n = int(input())

x = []
y = []

parity = -1
Have = True

for i in range(n):
    s = input().split(' ')
    x.append(int(s[0]))
    y.append(int(s[1]))

    p = (x[i] + y[i] + 10**10) % 2

    if (parity < 0):
        parity = p
    if (parity != p):
        Have = False

def Abs(v):
    if (v > 0): return  v
    else:       return -v

if (Have == False):
    print("-1")
else:
    arms = []

    for i in range(39):
        arms.append(2 ** (38 - i))

    if (parity == 0):
        arms.append(1)
        for i in range(n):
            x[i] -= 1

    print(len(arms))

    for v in arms:
        print(v,end = " ")

    print("")

    dx = [-1,0,1,0]
    dy = [0,-1,0,1]
    dir = ['L','D','R','U']

    for i in range(n):
        posX = 0
        posY = 0
        for j in range(39):
            for k in range(4):
                nxtX = posX + dx[k] * arms[j]
                nxtY = posY + dy[k] * arms[j]

                if (Abs(x[i] - nxtX) + Abs(y[i] - nxtY) < arms[j]):
                    print(dir[k],end = "")
                    posX = nxtX
                    posY = nxtY
                    break

        if (parity == 0):
            print("R")
        else:
            print("")

# coding: utf-8
# Your code here!

import numpy as np

def canbe_solved(positions):
    odd_evens = [np.dot(p,np.ones(2,int)) %2 for p in positions]
    if len(set(odd_evens)) == 1:
        return True
    else:
        return False

def solutions(p,vals):
    u = np.dot(p, np.array([1,1]))
    v = np.dot(p, np.array([1,-1]))
    for val in vals:
        if u >=0:
            if v >= 0:
                print('R',end="")
                u -= val
                v -= val
            else:
                print('U',end="")
                u -= val
                v += val
        else:
            if v >= 0:
                print('D',end="")
                u += val
                v -= val
            else:
                print('L',end="")
                u += val
                v += val
    print()

def main():
    #input
    n = int(input().rstrip())
    positions = [np.asarray(list(map(int,input().rstrip().split()))) for _ in range(n)]
    vals = [1<<i for i in range(30,-1,-1)]
    if np.dot(positions[0], np.ones(2,int)) % 2 == 0:
        vals.append(1)

    if canbe_solved(positions):
        print(len(vals))
        for i,p in enumerate(vals):
            print(p,end="")
            if i == len(vals)-1:
                print('')
            else:
                print(' ', end="")

        for p in positions:
            solutions(p,vals)
    else:
        print('-1')

main()

Score : <var>600</var> points

Problem Statement

Snuke is introducing a robot arm with the following properties to his factory:

The robot arm consists of <var>m</var> sections and <var>m+1</var> joints. The sections are numbered <var>1</var>, <var>2</var>, ..., <var>m</var>, and the joints are numbered <var>0</var>, <var>1</var>, ..., <var>m</var>. Section <var>i</var> connects Joint <var>i-1</var> and Joint <var>i</var>. The length of Section <var>i</var> is <var>d_i</var>.

For each section, its mode can be specified individually. There are four modes: L, R, D and U. The mode of a section decides the direction of that section. If we consider the factory as a coordinate plane, the position of Joint <var>i</var> will be determined as follows (we denote its coordinates as <var>(x_i, y_i)</var>):

<var>(x_0, y_0) = (0, 0)</var>.

If the mode of Section <var>i</var> is L, <var>(x_{i}, y_{i}) = (x_{i-1} - d_{i}, y_{i-1})</var>.

If the mode of Section <var>i</var> is R, <var>(x_{i}, y_{i}) = (x_{i-1} + d_{i}, y_{i-1})</var>.

If the mode of Section <var>i</var> is D, <var>(x_{i}, y_{i}) = (x_{i-1}, y_{i-1} - d_{i})</var>.

If the mode of Section <var>i</var> is U, <var>(x_{i}, y_{i}) = (x_{i-1}, y_{i-1} + d_{i})</var>.

Snuke would like to introduce a robot arm so that the position of Joint <var>m</var> can be matched with all of the <var>N</var> points <var>(X_1, Y_1), (X_2, Y_2), ..., (X_N, Y_N)</var> by properly specifying the modes of the sections.
Is this possible?
If so, find such a robot arm and how to bring Joint <var>m</var> to each point <var>(X_j, Y_j)</var>.

Constraints

All values in input are integers.

<var>1 \leq N \leq 1000</var>

<var>-10^9 \leq X_i \leq 10^9</var>

<var>-10^9 \leq Y_i \leq 10^9</var>

Partial Score

In the test cases worth <var>300</var> points, <var>-10 \leq X_i \leq 10</var> and <var>-10 \leq Y_i \leq 10</var> hold.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X_1</var> <var>Y_1</var>
<var>X_2</var> <var>Y_2</var>
<var>:</var>
<var>X_N</var> <var>Y_N</var>

Output

If the condition can be satisfied, follow the following format. If the condition cannot be satisfied, print -1.

<var>m</var>
<var>d_1</var> <var>d_2</var> <var>...</var> <var>d_m</var>
<var>w_1</var>
<var>w_2</var>
<var>:</var>
<var>w_N</var>

<var>m</var> and <var>d_i</var> are the configurations of the robot arm. Refer to the problem statement for what each of them means.
Here, <var>1 \leq m \leq 40</var> and <var>1 \leq d_i \leq 10^{12}</var> must hold. Also, <var>m</var> and <var>d_i</var> must all be integers.

<var>w_j</var> is a string of length <var>m</var> that represents the way to bring Joint <var>m</var> of the robot arm to point <var>(X_j, Y_j)</var>.
The <var>i</var>-th character of <var>w_j</var> should be one of the letters L, R, D and U, representing the mode of Section <var>i</var>.

Sample Input 1

3
-1 0
0 3
2 -1

Sample Output 1

2
1 2
RL
UU
DR

In the given way to bring Joint <var>m</var> of the robot arm to each <var>(X_j, Y_j)</var>, the positions of the joints will be as follows:

To <var>(X_1, Y_1) = (-1, 0)</var>: First, the position of Joint <var>0</var> is <var>(x_0, y_0) = (0, 0)</var>. As the mode of Section <var>1</var> is R, the position of Joint <var>1</var> is <var>(x_1, y_1) = (1, 0)</var>. Then, as the mode of Section <var>2</var> is L, the position of Joint <var>2</var> is <var>(x_2, y_2) = (-1, 0)</var>.

To <var>(X_2, Y_2) = (0, 3)</var>: <var>(x_0, y_0) = (0, 0), (x_1, y_1) = (0, 1), (x_2, y_2) = (0, 3)</var>.

To <var>(X_3, Y_3) = (2, -1)</var>: <var>(x_0, y_0) = (0, 0), (x_1, y_1) = (0, -1), (x_2, y_2) = (2, -1)</var>.

Sample Input 2

5
0 0
1 0
2 0
3 0
4 0

Sample Output 2

-1

Sample Input 3

2
1 1
1 1

Sample Output 3

2
1 1
RU
UR

There may be duplicated points among <var>(X_j, Y_j)</var>.

Sample Input 4

3
-7 -3
7 3
-3 -7

Sample Output 4

5
3 1 4 1 5
LRDUL
RDULR
DULRD


N=int(input())
xy=[tuple(map(int,input().split())) for i in range(N)]
xysum=[abs(xy[i][0])+abs(xy[i][1]) for i in range(N)]
can=1
for i in range(N-1):
    if xysum[i]%2!=xysum[i+1]%2:
        can=0
if can:
    xymax=max(xysum)
    if xymax==0:
        xymax=2
        print("1 1")
    else:
        for i in range(xymax-1):
            print("1 ",end='')
        print("1")
    for i in range(N):
        s=""
        if xy[i][0]>0:
            s+="R"*xy[i][0]
        else:
            s+="L"*(-1*xy[i][0])
        if xy[i][1]>0:
            s+="U"*xy[i][1]
        else:
            s+="D"*(-1*xy[i][1])
        for i in range((xymax-xysum[i])//2):
            s+="RL"
        print(s)
else:
    print(-1)


import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush

input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

def main():
    N, X = MI()
    L = LI()
    L = [abs(i-X) for i in L]
    ans = L[0]
    for i in L:
        ans = math.gcd(ans, i)
    print(ans)

if __name__ == "__main__":
    main()

def gcd(x, y):
    if y == 0:
        return x
    else:
        return gcd(y, x % y)

n, x = map(int, input().split())
xxx = list(map(lambda xn: abs(int(xn) - x), input().split()))
ans = xxx[0]
for i in range(1, n):
    ans = gcd(ans, xxx[i])
print(ans)

Score : <var>300</var> points

Problem Statement

There are <var>N</var> cities on a number line. The <var>i</var>-th city is located at coordinate <var>x_i</var>.

Your objective is to visit all these cities at least once.

In order to do so, you will first set a positive integer <var>D</var>.

Then, you will depart from coordinate <var>X</var> and perform Move <var>1</var> and Move <var>2</var> below, as many times as you like:

Move <var>1</var>: travel from coordinate <var>y</var> to coordinate <var>y + D</var>.

Move <var>2</var>: travel from coordinate <var>y</var> to coordinate <var>y - D</var>.

Find the maximum value of <var>D</var> that enables you to visit all the cities.

Here, to visit a city is to travel to the coordinate where that city is located.

Constraints

All values in input are integers.

<var>1 \leq N \leq 10^5</var>

<var>1 \leq X \leq 10^9</var>

<var>1 \leq x_i \leq 10^9</var>

<var>x_i</var> are all different.

<var>x_1, x_2, ..., x_N \neq X</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>X</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Output

Print the maximum value of <var>D</var> that enables you to visit all the cities.

Sample Input 1

3 3
1 7 11

Sample Output 1

2

Setting <var>D = 2</var> enables you to visit all the cities as follows, and this is the maximum value of such <var>D</var>.

Perform Move <var>2</var> to travel to coordinate <var>1</var>.

Perform Move <var>1</var> to travel to coordinate <var>3</var>.

Perform Move <var>1</var> to travel to coordinate <var>5</var>.

Perform Move <var>1</var> to travel to coordinate <var>7</var>.

Perform Move <var>1</var> to travel to coordinate <var>9</var>.

Perform Move <var>1</var> to travel to coordinate <var>11</var>.

Sample Input 2

3 81
33 105 57

Sample Output 2

24

Sample Input 3

1 1
1000000000

Sample Output 3

999999999


n,x=map(int, input().split())
x_list=[int(i) for i in input().split()]

x_list.append(x)
x_list.sort()
sa=[]
for i in range(n):
    sa.append(x_list[i+1]-x_list[i])

print(min(sa))


L = int(input())
N = len(str(bin(L)))-3
E = []

for n in range(N):
  E.append((n+1,n+2,0))
  E.append((n+1,n+2,2**(N-n-1)))

H = 2**N

for i,c in enumerate(str(bin((L)))[2:]):
    if c=="1" and i:
      E.append((1,i+1,H))
      H+=2**(N-i)

print(N+1,len(E))
for e in E:
  print(*e)

l=int(input())
for i in range(1,21):
	if 2**i>l:
		r=i-1
		break
ans=[]
for i in range(r):
	ans.append((i+1,i+2,0))
	ans.append((i+1,i+2,2**i))
now=2**r-1
for i in range(r,0,-1):
	if 2**(i-1)+now<=l-1:
		ans.append((i,r+1,now+1))
		now+=2**(i-1)
print(r+1,len(ans))
for x in ans:
	print(*x)

Score : <var>700</var> points

Problem Statement

You are given an integer <var>L</var>. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.

The number of vertices, <var>N</var>, is at most <var>20</var>. The vertices are given ID numbers from <var>1</var> to <var>N</var>.

The number of edges, <var>M</var>, is at most <var>60</var>. Each edge has an integer length between <var>0</var> and <var>10^6</var> (inclusive).

Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, <var>1,2,...,N</var> is one possible topological order of the vertices.

There are exactly <var>L</var> different paths from Vertex <var>1</var> to Vertex <var>N</var>. The lengths of these paths are all different, and they are integers between <var>0</var> and <var>L-1</var>.

Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.

Constraints

<var>2 \leq L \leq 10^6</var>

<var>L</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>L</var>

Output

In the first line, print <var>N</var> and <var>M</var>, the number of the vertices and edges in your graph.
In the <var>i</var>-th of the following <var>M</var> lines, print three integers <var>u_i,v_i</var> and <var>w_i</var>, representing the starting vertex, the ending vertex and the length of the <var>i</var>-th edge.
If there are multiple solutions, any of them will be accepted.

Sample Input 1

4

Sample Output 1

8 10
1 2 0
2 3 0
3 4 0
1 5 0
2 6 0
3 7 0
4 8 0
5 6 1
6 7 1
7 8 1

In the graph represented by the sample output, there are four paths from Vertex <var>1</var> to <var>N=8</var>:

<var>1</var> → <var>2</var> → <var>3</var> → <var>4</var> → <var>8</var> with length <var>0</var>

<var>1</var> → <var>2</var> → <var>3</var> → <var>7</var> → <var>8</var> with length <var>1</var>

<var>1</var> → <var>2</var> → <var>6</var> → <var>7</var> → <var>8</var> with length <var>2</var>

<var>1</var> → <var>5</var> → <var>6</var> → <var>7</var> → <var>8</var> with length <var>3</var>

There are other possible solutions.

Sample Input 2

5

Sample Output 2

5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1


#!/usr/bin/env python3

import math

l = int(input())

r = math.floor(math.log2(l))

num_vertex = 0
num_edge = 0

num_vertex += r+2

print_list = []
for i in range(r):
    print_list.append([i+1, i+2, 0])
    print_list.append([i+1, i+2, 2**i])
    num_edge += 2

for i in reversed(range(r+1)):
    if l-2**i >= 2**r:
        print_list.append([i+1, r+1, l-2**i])
        l -= 2**i
        num_edge += 1

print(num_vertex, num_edge)
for i in print_list:
    print(*i)


def solve():
    MOD = 998244353
    maxNK = 2000

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

    def getInvs(n, MOD):
        invs = [1] * (n+1)
        for x in range(2, n+1):
            invs[x] = (-(MOD//x) * invs[MOD%x]) % MOD
        return invs

    def getCombss(n, k, invs, MOD):
        def getCombNs(n, k, invs, MOD):
            combNs = [1] * (n//2+1)
            for x in range(1, n//2+1):
                combNs[x] = (combNs[x-1] * (n-x+1) * invs[x]) % MOD
            return (combNs + combNs[:(n+1)//2][::-1])[:k+1]
        combss = [[] for n in range(n+1)]
        for x in range(n+1):
            combss[x] = getCombNs(x, k, invs, MOD)
            combss[x] += [0] * (k+1-len(combss[x]))
        return combss

    invs = getInvs(2*maxNK, MOD)
    combss = getCombss(2*maxNK, maxNK, invs, MOD)

    def getPows(base, n, MOD):
        pows = [1] * (n+1)
        for x in range(1, n+1):
            pows[x] = (pows[x-1] * base) % MOD
        return pows
    pow2s = getPows(2, N, MOD)

    anss = []
    for i in range(2, K+2, 2):
        ans = 0
        numFree = abs(K+1-i)
        numPair = (K-numFree+1)//2
        numPair -= 1
        for x in range(min(numPair, N)+1):
            ans += combss[numPair][x] * pow2s[x] * combss[N+numFree-1][N-x] % MOD
            ans %= MOD
        for x in range(min(numPair, N)+1):
            ans += combss[numPair][x] * pow2s[x] * combss[N+numFree-2][N-x-1] % MOD
            ans %= MOD
        anss.append(ans)
        if i+1 <= K+1:
            anss.append(ans)

    anss = anss + anss[:-1][::-1]
    print('\n'.join(map(str, anss)))

solve()

import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def nCr(com_n, com_r):
    if com_n < com_r: return 0
    return fac[com_n] * ifac[com_r] % md * ifac[com_n - com_r] % md

def nHr(hn,hr):
    return nCr(hn+hr-1,hr)

md = 998244353
n_max = 5000
fac = [1]
for i in range(1, n_max + 1): fac.append(fac[-1] * i % md)
ifac = [1] * (n_max + 1)
ifac[n_max] = pow(fac[n_max], md - 2, md)
for i in range(n_max - 1, 1, -1): ifac[i] = ifac[i + 1] * (i + 1) % md

def solve():
    res=0
    for p in range(min(t,n)//2+1):
        cur=nCr(t//2,p)*nHr(k,n-2*p)
        if p&1:res-=cur
        else:res+=cur
        res%=md
    return res

k,n=MI()
ans=[]
for t in range(2,k+2):
    a=solve()
    ans.append(a)
    print(a)
ans.reverse()
for a in ans[1:]:print(a)

Score : <var>700</var> points

Problem Statement

Takahashi throws <var>N</var> dice, each having <var>K</var> sides with all integers from <var>1</var> to <var>K</var>. The dice are NOT pairwise distinguishable.
For each <var>i=2,3,...,2K</var>, find the following value modulo <var>998244353</var>:

The number of combinations of <var>N</var> sides shown by the dice such that the sum of no two different sides is <var>i</var>.

Note that the dice are NOT distinguishable, that is, two combinations are considered different when there exists an integer <var>k</var> such that the number of dice showing <var>k</var> is different in those two.

Constraints

<var>1 \leq K \leq 2000</var>

<var>2 \leq N \leq 2000</var>

<var>K</var> and <var>N</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var> <var>N</var>

Output

Print <var>2K-1</var> integers. The <var>t</var>-th of them <var>(1\leq t\leq 2K-1)</var> should be the answer for <var>i=t+1</var>.

Sample Input 1

3 3

Sample Output 1

7
7
4
7
7

For <var>i=2</var>, the combinations <var>(1,2,2),(1,2,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3)</var> satisfy the condition, so the answer is <var>7</var>.

For <var>i=3</var>, the combinations <var>(1,1,1),(1,1,3),(1,3,3),(2,2,2),(2,2,3),(2,3,3),(3,3,3)</var> satisfy the condition, so the answer is <var>7</var>.

For <var>i=4</var>, the combinations <var>(1,1,1),(1,1,2),(2,3,3),(3,3,3)</var> satisfy the condition, so the answer is <var>4</var>.

Sample Input 2

4 5

Sample Output 2

36
36
20
20
20
36
36

Sample Input 3

6 1000

Sample Output 3

149393349
149393349
668669001
668669001
4000002
4000002
4000002
668669001
668669001
149393349
149393349


def cmb(n,r):
  if n<=0:
    return 0
  elif r<0:
    return 0
  elif r>n:
    return 0
  elif r==0:
    return 1
  elif r==n:
    return 1
  else:
    return A[n]*B[r]*B[n-r]%mod
mod=998244353
A=[1,1]
B=[1,1]
for i in range(2,4005):
  A.append(A[-1]*i%mod)
  B.append(B[-1]*pow(i,mod-2,mod)%mod)
k,n=map(int,input().split())
if k==1:
  print(0)
  exit()
ans=[0]*(2*k+1)
for i in range(2,k+3):#i,i+1(i%2=0,i<k(くらい))で同じとか自明か？？？？？
  if i%2==0:
    i=i+1
    for j in range(min(n+1,i//2+1)):
      ans[i-1]=(ans[i-1]+cmb(n+k-i,k-i+j)*cmb(i//2,j)*pow(2,j,mod))%mod
  else:
    ans[i]=ans[i-1]
for i in range(k+2,2*k+1):
  ans[i]=ans[2*k+2-i]
for i in range(2,2*k+1):
  print(ans[i])


def main():
    n, i = list(map(int, input().split()))
    print(n-i+1)

if __name__ == '__main__':
    main()

Score : <var>100</var> points

Problem Statement

There is an <var>N</var>-car train.

You are given an integer <var>i</var>. Find the value of <var>j</var> such that the following statement is true: "the <var>i</var>-th car from the front of the train is the <var>j</var>-th car from the back."

Constraints

<var>1 \leq N \leq 100</var>

<var>1 \leq i \leq N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>i</var>

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a <var>4</var>-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


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

print(N + i - 1)


import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush

input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

def main():
    N = I()
    if N == 0:
        print(0)
        exit()
    if N < 0:
        N = -N
        D = defaultdict(int)
        index = 0
        while N >= 1:
            #bitフラグがたっていたら
            if N & 1 == 1:
                #2の倍数の場合D[index]とD[index+1]に1を足す
                if index % 2 == 0:
                    D[index] += 1
                    D[index+1] += 1
                else:
                    D[index] += 1
            else:
                D[index] = D[index]
            N = N>>1
            index += 1
    else:
        D = defaultdict(int)
        if N & 1 == 1:
            D[0] = 1
        else:
            D[0] = 0
        index = 1
        N = N >> 1

        while N >= 1:
            #bitフラグがたっていたら
            if N & 1 == 1:
                #2の倍数の場合D[index]とD[index+1]に1を足す
                if index % 2 == 1:
                    D[index] += 1
                    D[index+1] += 1
                else:
                    D[index] += 1
            else:
                D[index] = D[index]
            N = N>>1
            index += 1

    index = 0
    while True:
        if not index in D.keys():
            break
        if D[index] <= 1:
            pass
        else:
            temp = D[index]
            D[index] = temp % 2
            D[index+1] += (temp // 2)
            D[index+2] += (temp // 2)
            if D[index+1] >= D[index+2] * 2:
                temp = D[index+2]
                D[index+2] -= temp
                D[index+1] -= temp * 2
        index += 1
    res = True

    for i in reversed(D.values()):
        if res and i == 1:
            res = False
        if not res:
            print(i, end="")
    print()

if __name__ == "__main__":
    main()

Score : <var>300</var> points

Problem Statement

Given an integer <var>N</var>, find the base <var>-2</var> representation of <var>N</var>.

Here, <var>S</var> is the base <var>-2</var> representation of <var>N</var> when the following are all satisfied:

<var>S</var> is a string consisting of 0 and 1.

Unless <var>S =</var> 0, the initial character of <var>S</var> is 1.

Let <var>S = S_k S_{k-1} ... S_0</var>, then <var>S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N</var>.

It can be proved that, for any integer <var>M</var>, the base <var>-2</var> representation of <var>M</var> is uniquely determined.

Constraints

Every value in input is integer.

<var>-10^9 \leq N \leq 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the base <var>-2</var> representation of <var>N</var>.

Sample Input 1

-9

Sample Output 1

1011

As <var>(-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9</var>, 1011 is the base <var>-2</var> representation of <var>-9</var>.

Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0


import sys
import math
from collections import defaultdict, deque, Counter
from copy import deepcopy
from bisect import bisect, bisect_right, bisect_left
from heapq import heapify, heappop, heappush

input = sys.stdin.readline
def RD(): return input().rstrip()
def F(): return float(input().rstrip())
def I(): return int(input().rstrip())
def MI(): return map(int, input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int, input().split()))
def TI(): return tuple(map(int, input().split()))
def LF(): return list(map(float,input().split()))
def Init(H, W, num): return [[num for i in range(W)] for j in range(H)]

def main():
    N = I()
    if N == 0:
        print(0)
        exit()
    if N < 0:
        N = -N
        D = defaultdict(int)
        index = 0
        while N >= 1:
            #bitフラグがたっていたら
            if N & 1 == 1:
                #2の倍数の場合D[index]とD[index+1]に1を足す
                if index % 2 == 0:
                    D[index] += 1
                    D[index+1] += 1
                else:
                    D[index] += 1
            else:
                D[index] = D[index]
            N = N>>1
            index += 1
    else:
        D = defaultdict(int)
        if N & 1 == 1:
            D[0] = 1
        else:
            D[0] = 0
        index = 1
        N = N >> 1

        while N >= 1:
            #bitフラグがたっていたら
            if N & 1 == 1:
                #2の倍数の場合D[index]とD[index+1]に1を足す
                if D[index] == 1:
                    D[index] += 1
                    D[index+1] += 1
                else:
                    D[index] += 1
                    D[index+1] += 1
            else:
                D[index] = D[index]
            N = N>>1
            index += 1
    index = 0
    while True:
        if not index in D.keys():
            break
        if D[index] <= 1:
            pass
        else:
            temp = D[index]
            D[index] = temp % 2
            D[index+1] = temp // 2
            D[index+2] = temp // 2
        index += 1

    for i in reversed(D.values()):
        print(i, end="")
    print()

if __name__ == "__main__":
    main()