s = list(input())
t = list(input())
tmp = 0
ans = len(t)
# j_tmp = 0
for i in range(len(s) - len(t) + 1):
    tmp = 0
    for j in range(len(t)):
        if s[i + j] != t[j]:
            tmp += 1
    if tmp < ans:
        ans = tmp
print(ans)

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


S = input()
T = input()

for i in range(len(T), 0, -1):
    for j in range(len(T)-i+1):
        subst = T[j:i+j]
#        print(subst)
        if S.find(subst, j, len(S)-(len(T)-i-j))>=0:
            print (len(T)-i)
            print(subst)
#            exit(0)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


s = input()
t = input()
n = len(s) - len(t) + 1
ans = 1000
for i in range(n):
    temp = 0
    for j in range(len(t)):
        if t[j] != s[j+i]:
            temp += 1
    ans = min(temp,ans)
print(temp)


from collections import Counter
N, M = map(int, input().split())
groups = [0] * (N + 1)
group_num_list = [[0]]
group_num = 1
for _ in range(M):
    A, B = map(int, input().split())
    if groups[A] != 0 and groups[B] != 0:
        if groups[A] != groups[B]:
            lower = min(groups[A], groups[B])
            higher = max(groups[A], groups[B])
            for i in group_num_list[higher]:
                groups[i] = lower
            tmp = group_num_list[higher]
            group_num_list[lower].extend(tmp)
            # del group_num_list[higher]
    elif groups[A] != 0:
        groups[B] = groups[A]
        group_num_list[groups[A]].append(B)
    elif groups[B] != 0:
        groups[A] = groups[B]
        group_num_list[groups[B]].append(A)
    else:
        groups[A] = group_num
        groups[B] = group_num
        group_num_list.append([A, B])
        group_num += 1
counter = Counter(groups)
# print(collection)
# print(group_num_list)
if counter.most_common()[0][0] != 0:
    print(counter.most_common()[0][1])
else:
    print(counter.most_common()[1][1])

Score : 400 points

Problem Statement

There are N persons called Person 1 through Person N.

You are given M facts that "Person A_i and Person B_i are friends." The same fact may be given multiple times.

If X and Y are friends, and Y and Z are friends, then X and Z are also friends. There is no friendship that cannot be derived from the M given facts.

Takahashi the evil wants to divide the N persons into some number of groups so that every person has no friend in his/her group.

At least how many groups does he need to make?

Constraints

2 \leq N \leq 2\times 10^5

0 \leq M \leq 2\times 10^5

1\leq A_i,B_i\leq N

A_i \neq B_i

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
\vdots
A_M B_M

Output

Print the answer.

Sample Input 1

5 3
1 2
3 4
5 1

Sample Output 1

3

Dividing them into three groups such as \{1,3\}, \{2,4\}, and \{5\} achieves the goal.

Sample Input 2

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

Sample Output 2

4

Sample Input 3

10 4
3 1
4 1
5 9
2 6

Sample Output 3

3


N, X, T = (int(a) for a in input().split())
print(math.ceil(N / X) * T)

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


n,x,t = map(int, input().split())
ko = 0
time = 0
while ko < n:
    time += t
    ko += x
print(time)


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

ans = (N + X - 1) // X * T

print (ans)


N = int(input())

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

current_max_height = 0

need_height = 0
for i in range(N):

    if As[i] > current_max_height:
        current_max_height = As[i]

    need_height += current_max_height - As[i]

print(need_height)

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


n=int(input())
a=list(map(int,input().split()))
num=0
k=a[0]
for i in a:
  if i>k:
    k=i
  if i<k:
    num+=(k-i)
print(num)


N = int(input())
A = list(map(int, input().split()))
prev = A[0]
ans = 0
for a in A[1:]:
    if prev <= a:
        prev = a
        continue
    ans += prev - a
print(ans)


h,w = map(int,input().split())
c = list(map(int,input().split()))
d = list(map(int,input().split()))
s = [list(input()) for _ in range(h)]

c[0] -= 1
c[1] -= 1
d[0] -= 1
d[1] -= 1

stack = []
q = [[c, 0]]
ans = -1
dt = [[h*w for _ in range(w)] for _ in range(h)]
dt[c[0]][c[1]] = 0
while q:
  #print("q: {}".format(q))
  pos,time = q.pop(0)
  stack = [pos]
  while stack:
    #print("stack: {}".format(stack))
    pos = stack.pop()
    if pos[0] == d[0] and pos[1] == d[1]:
      ans = time
      q = []
      break
    for i in range(-2,3):
      for j in range(-2,3):
        if i==0 and j==0:
          continue
        elif (i==0 and j >=-1 and j <= 1) or (j==0 and i >=-1 and i <= 1):
          if (pos[0]+i>-1 and pos[0]+i<h and pos[1]+j>-1 and pos[1]+j<w
              and s[pos[0]+i][pos[1]+j]=="."):
            stack.append([pos[0]+i, pos[1]+j])
            s[pos[0]+i][pos[1]+j] = "#"
            dt[pos[0]+i][pos[1]+j] = time
        else:
          if (pos[0]+i>-1 and pos[0]+i<h and pos[1]+j>-1 and pos[1]+j<w
              and s[pos[0]+i][pos[1]+j]=="." and dt[pos[0]+i][pos[1]+j]>time+1):
            q.append([[pos[0]+i, pos[1]+j],time+1])
            dt[pos[0]+i][pos[1]+j] = time+1

print(ans)

Score : 400 points

Problem Statement

A maze is composed of a grid of H \times W squares - H vertical, W horizontal.

The square at the i-th row from the top and the j-th column from the left - (i,j) - is a wall if S_{ij} is # and a road if S_{ij} is ..

There is a magician in (C_h,C_w). He can do the following two kinds of moves:

Move A: Walk to a road square that is vertically or horizontally adjacent to the square he is currently in.

Move B: Use magic to warp himself to a road square in the 5\times 5 area centered at the square he is currently in.

In either case, he cannot go out of the maze.

At least how many times does he need to use the magic to reach (D_h, D_w)?

Constraints

1 \leq H,W \leq 10^3

1 \leq C_h,D_h \leq H

1 \leq C_w,D_w \leq W

S_{ij} is # or ..

S_{C_h C_w} and S_{D_h D_w} are ..

(C_h,C_w) \neq (D_h,D_w)

Input

Input is given from Standard Input in the following format:

H W
C_h C_w
D_h D_w
S_{11}\ldots S_{1W}
\vdots
S_{H1}\ldots S_{HW}

Output

Print the minimum number of times the magician needs to use the magic. If he cannot reach (D_h,D_w), print -1 instead.

Sample Input 1

4 4
1 1
4 4
..#.
..#.
.#..
.#..

Sample Output 1

1

For example, by walking to (2,2) and then using the magic to travel to (4,4), just one use of magic is enough.

Note that he cannot walk diagonally.

Sample Input 2

4 4
1 4
4 1
.##.
####
####
.##.

Sample Output 2

-1

He cannot move from there.

Sample Input 3

4 4
2 2
3 3
....
....
....
....

Sample Output 3

0

No use of magic is needed.

Sample Input 4

4 5
1 2
2 5
#.###
####.
#..##
#..##

Sample Output 4

2


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

def main():
    S = sys.stdin.readline().rstrip()

    prev = ""
    cnt = 0
    cnt_max = 0

    for char in S:
        if char == "R":
            cnt += 1
        elif char == "S":
            cnt = 0

        cnt_max = max(cnt_max, cnt)

    print(cnt_max)

if __name__ == "__main__":
    main()

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


s=input()

con=False

ans=0
for i in range(3):
  if(s[i]=="R" and con):
    ans+=1
  elif(s[i]=="R" and not(con)):
    ans=1
    con=True
  else:
    con=False

print(ans)


S=input().strip("¥n")

if S=="RRR":
	print(3)
elif "RR" in S:
	print(2)
elif "R" in S:
	print(1)
else:
	print(0)


def resolve():
    S = input()
    if "RRR" in S:
        print(3)
    elif "RR" in S:
        print(2)
    elif "R" in S:
        print(1)
    else:
        print(0)
resolve()


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

if k <= x//d:
    ans = abs(x-k*d)
else:
    if (k-x//d)%2!=0:
        ans = abs(x-(x//d+1)*d)
    else:
        ans = abs(x-(x//d)*d)

print(ans)

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


x, k, d = map(int, input().split())  # x現在地,k 移動回数,D移動できる距離
a = x // d  # 移動できる回数
b = x % d  # 移動した特のあまり
if k <= a:  # 移動する回数がkより大きいとき
    x = x - (k*d)
else:
    k = k - a  # ここで最短
    if k % 2 == 0:
        if x >= 0:
            x = x - (a * d)
        else:
            x = x + (a * d)
    else:
        x = x - (a * d)
        if x >= 0:
            x = x - abs(d)
        else:
            x = x + abs(d)

print(abs(x))


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

if x-k*d>=0:
    print(x-k*d)
else:
    n=x//d
    k-=n
    a=x-n*d
    if k%2==0:
        print(min(a,2*d-a))
    else:
        print(min(d-a,a+d))


n, k = map(int, input().split())
P = [*map(lambda x: int(x)-1, input().split())]
C = [*map(int, input().split())]

INF = 10**18
max_score = -INF
for st in range(n):
    lc = 0 # lap count
    lap_sc = 0 # lap score
    nx = st
    while True:
        lc += 1
        lap_sc += C[nx]
        nx = P[nx]
        if nx == st: break

    sum_sc = 0
    kc = 0
    while True:
        kc += 1
        if k < kc: break

        sum_sc += C[nx]
        score = sum_sc + max(0, lap_sc) * ((k - kc) // lc)
        max_score = max(max_score, score)

        nx = P[nx]
        if nx == st: break

print(max_score)

# print('===')
# print(n,k)
# print(P)
# print(C,end='\n\n')

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


import numpy as np
from numpy.fft import rfft,irfft

p = 200003
N = int(input())
A = list(map(int,input().split()))
a = np.zeros(2*p)

g = 1
d = {}
p2 = [1]*p
for i in range(p):
    d[g] = i
    p2[i] = g
    g *= 2
    g %= p

for i in range(N):
    if A[i]==0:
        continue
    a[d[A[i]]] += 1

b = rfft(a)
b = irfft(b*b)
b = [int(x+0.5) for x in b]

ans = 0
for i in range(p):
    ans += (b[i]+b[i+p-1])*p2[i]

for i in range(N):
    ans -= A[i]**2%p
ans //= 2
print(ans)

Score : 800 points

Problem Statement

Let’s take a prime P = 200\,003.
You are given N integers A_1, A_2, \ldots, A_N.
Find the sum of ((A_i \cdot A_j) \bmod P) over all N \cdot (N-1) / 2 unordered pairs of elements (i < j).

Please note that the sum isn't computed modulo P.

Constraints

2 \leq N \leq 200\,000

0 \leq A_i < P = 200\,003

All values in input are integers.

Input

Input is given from Standard Input in the following format.

N
A_1 A_2 \cdots A_N

Output

Print one integer — the sum over ((A_i \cdot A_j) \bmod P).

Sample Input 1

4
2019 0 2020 200002

Sample Output 1

474287

The non-zero products are:

2019 \cdot 2020 \bmod P = 78320

2019 \cdot 200002 \bmod P = 197984

2020 \cdot 200002 \bmod P = 197983

So the answer is 0 + 78320 + 197984 + 0 + 0 + 197983 = 474287.

Sample Input 2

5
1 1 2 2 100000

Sample Output 2

600013


val = int(input())
if val>=30:
    print('Yes')
else:
    print('No')

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


X=int(input())
if X>=30:
	print("Yes")
else:
	print("No")


# input here
_INPUT = """\
4 5
0 5
-2 4
3 4
4 -4
"""

def main():
    # -*- coding: utf-8 -*-
    # スペース区切りの整数の入力
    N, D = map(int, input().split())
    xy = [list(map(int, input().split())) for i in range(N)]

    answer = []

    for j in range(len(xy)):
        # 距離求める
        distance = math.sqrt((xy[j][0]**2 + xy[j][1]**2))

        # Dとdistance比較する
        if D >= distance:
            answer.append(distance)

    print(len(answer))

if __name__ == '__main__':
    import io
    import sys
    import math

    # sys.stdin = io.StringIO(_INPUT)
    main()

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

1 \leq N \leq 2\times 10^5

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


k = int(input())
mod = 0

for i in range(1, k + 1):
    mod = ((mod * 10) % k + 7) % k
    if mod == 0:
        print(i)
        break
else:
    print(-1)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


K = int(input())

N = 0

for i in range(10001):
    N += 7*(10**i)
    if N%K ==0:
        print(i)
        break
else:
    print(-1)


def main(k):
    size, res = 1, 7 % k
    while res and size <= 1_000_000:
        res = (res * 10 + 7) % k
        size += 1
    return -1 if size > 1_000_000 else size

if __name__ == '__main__':
    k = int(input())
    print(main(k))


A, B, C = input().split()
A = int(A)
B = int(B)
C = int(C)
K = input()
K = int(K)
z = 0
while B > A:
    B = B * 2
    z = z + 1
while C > B:
    C = C * 2
    z = z + 1
if K < z:
    print('NO')
else:
    print('YES')

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


N, K = map(int, input().split())
A = [int(i) for i in input().split()]
for i in range(K,N):
    a = A[i-K]
    b = A[i]
    if a<b: print('Yes')
    else: print('No')

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

15 7
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


N,K=map(int,input().split())
A=list(map(int,input().split()))
A_max=max(A)
for i in range(N):
    A[i]=A[i]/A_max
ans=list()
tmp=1
for i in range(K):
    tmp=tmp*A[i]
for i in range(K,N):
    tmp_old=tmp
    tmp=tmp_old*A[i]/A[i-K]
    if tmp_old<tmp:
        ans.append('Yes')
    else:
        ans.append('No')
for i in ans:
    print(i)


import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
#======================================================#
def main():
    l, r, d = MII()
    cnt = 0
    for i in range(l, r+1):
        if i%d == 0:
            cnt += 1
    print(cnt)

if __name__ == '__main__':
    main()

Score : 100 points

Problem Statement

How many multiples of d are there among the integers between L and R (inclusive)?

Constraints

All values in input are integers.

1 \leq L \leq R \leq 100

1 \leq d \leq 100

Input

Input is given from Standard Input in the following format:

L R d

Output

Print the number of multiples of d among the integers between L and R (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between 5 and 10, there are three multiples of 2: 6, 8, and 10.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between 6 and 20, there are two multiples of 7: 7 and 14.

Sample Input 3

1 100 1

Sample Output 3

100


N=int(input())
for n in range(1,N+1):
    ans=0
    for x in range(1,101):
        tx=x**2
        if tx>n-2*x :
            break
        for y in range(x,101-x):
            ty=tx+y**2+x*y
            if ty>n-x-y :
                break
            ss=(x+y)**2-4*(ty-n)
            if ss<0:
                break
            s=ss**0.5
            if s.is_integer():
                z=int((-1*(x+y)+s)/2)
                if z>=y:

                    if len(set([x,y,z]))==1:
                        ans+=1
                    if len(set([x,y,z]))==2:
                        ans+=3
                    if len(set([x,y,z]))==3:
                        ans+=6
    print(ans)

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


import collections
n = int(input())
dic = collections.defaultdict(int)
for i in range(n):
  dic[input()] += 1
print("AC x" + dic["AC"])
print("WA x" + dic["WA"])
print("TLE x" + dic["TLE"])
print("RE x" + dic["RE"])

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


import sys

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

def main():
    N = int(readline())
    S = [readline().strip() for _ in range(N)]

    for s in ['AC', 'WA', 'TLE', 'RE']:
        print(f'{s} x {S.count(s)}')

    return

if __name__ == '__main__':
    main()


# C - H and V
import sys

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

def main():
    H, W, K = map(int, readline().split())
    C = [line.decode() for line in readlines()]
    res = 0
    for bit in range(1 << (H + W)):
        cnt_black = sum(
            C[i][j] == "#" and not (bit >> i) & 1 and not (bit >> (j + H)) & 1
            for i in range(H)
            for j in range(W)
        )
        if cnt_black == K:
            res += 1
    print(res)

if __name__ == "__main__":
    main()

Score : 300 points

Problem Statement

We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is ., and black if c_{i,j} is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer K. How many choices of rows and columns result in exactly K black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

1 \leq H, W \leq 6

1 \leq K \leq HW

c_{i,j} is . or #.

Input

Input is given from Standard Input in the following format:

H W K
c_{1,1}c_{1,2}...c_{1,W}
c_{2,1}c_{2,2}...c_{2,W}
:
c_{H,1}c_{H,2}...c_{H,W}

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The 1-st row and 1-st column

The 1-st row and 2-nd column

The 1-st row and 3-rd column

The 1-st and 2-nd column

The 3-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208


import sys
import math
import collections
import heapq

def set_debug(debug_mode=False):
    if debug_mode:
        fin = open('input.txt', 'r')
        sys.stdin = fin

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

if __name__ == '__main__':
    # set_debug(True)

    # t = int(input())
    t = 1

    for ti in range(1, t + 1):
        n = int(input())

        A = int_input()

        A.sort()

        res = A[-1]
        for i in range(len(A)-2):
            res += A[-(i//2)-2]
        print(res)

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


#!/usr/bin/env python3
from functools import reduce

mod = 10**9 + 7
n, k, *a = map(int, open(0).read().split())
a.sort(key=lambda x: abs(x))
ans = reduce(lambda a, b: (a * b) % mod, a[-k:])

c = a[-k:]
j = sum(i < 0 for i in c) % 2
if j:
    c = a[-k:]
    neg = [i for i in c if i < 0]
    pos = [i for i in c if i > 0]
    b = sorted(a[:n - k])
    if b == []:
        print(ans)
        exit()
    if neg == []:
        if pos[0] * b[0] < 0:
            ans = ans * pow(pos[0], mod - 2, mod) * b[0] % mod
        else:
            ans = reduce(lambda a, b: (a * b) % mod, a[:k])
    elif pos == []:
        if neg[0] * b[-1] < 0:
            ans = ans * pow(neg[0], mod - 2, mod) * b[-1] % mod
        else:
            ans = reduce(lambda a, b: (a * b) % mod, a[:k])
    elif pos[0] * b[-1] > neg[0] * b[0] and pos[0] * b[0] < 0:
        ans = ans * pow(pos[0], mod - 2, mod) * b[0] % mod
    elif 0 > b[-1] * neg[0]:
        ans = ans * pow(neg[0], mod - 2, mod) * b[-1] % mod
    else:
        ans = reduce(lambda a, b: (a * b) % mod, a[:k])
print(ans)

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

1 \leq K \leq N \leq 2\times 10^5

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


#[int(i) for i in input().split()]
s = input()
t = input()
ans = 0
for i in range(len(s)):
    if s[i] != t[i]:
        ans += 1
print(ans)

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


def prepare(n):
    global MOD
    modFacts = [0] * (n + 1)
    modFacts[0] = 1
    for i in range(n):
        modFacts[i + 1] = (modFacts[i] * (i + 1)) % MOD

    invs = [1] * (n + 1)
    invs[n] = pow(modFacts[n], MOD - 2, MOD)
    for i in range(n, 1, -1):
        invs[i - 1] = (invs[i] * i) % MOD

    return modFacts, invs

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

MOD = 10 ** 9 + 7
modFacts, invs = prepare(max(N, M))

ans = 0
for i in range(N + 1):
    Ti = (modFacts[N] * invs[i] * invs[N - i]) % MOD
    Ti *= (modFacts[M] * invs[M - i]) % MOD
    Ti %= MOD
    Ti *= pow(modFacts[M - i] * invs[(M - i) - (N - i)], 2, MOD)
    Ti %= MOD
    ans += pow(-1, i) * Ti
    ans %= MOD

print(ans)

Score : 500 points

Problem Statement

Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions:

A_i \neq B_i, for every i such that 1\leq i\leq N.

A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N.

Since the count can be enormous, print it modulo (10^9+7).

Constraints

1\leq N \leq M \leq 5\times10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the count modulo (10^9+7).

Sample Input 1

2 2

Sample Output 1

2

A_1=1,A_2=2,B_1=2,B_2=1 and A_1=2,A_2=1,B_1=1,B_2=2 satisfy the conditions.

Sample Input 2

2 3

Sample Output 2

18

Sample Input 3

141421 356237

Sample Output 3

881613484


import sys
import math
#import random
#sys.setrecursionlimit(1000000)
input = sys.stdin.readline

############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
    return(int(input()))
def inara():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############

a=input()

if a>='a' and a<='z':
	print("a")
else:
	print("A")

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


def main():
    nmax = 100000
    n = int(input())
    values = [0] * nmax
    a = [int(v) for v in input().split()]
    for v in a:
        values[v-1] += 1
    asum = sum(a)

    q = int(input())
    for _ in range(q):
        b, c = [int(v) for v in input().split()]
        asum += values[b-1] * (c - b)
        values[c-1] += values[b-1]
        values[b-1] = 0
        print(asum)

main()


Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


n = input()
m = n.split()
print(m)
a = [input() for l in range(0,1)]
b = a[0].split()
print(b)

for i in range(0, len(b)):
    b[i] = int(b[i])

c = sorted(b, reverse=True)
print(c)
p = 0
for i in range(int(m[0]) - int(m[1]),int(m[0])):
    p = p + int(c[i])
print(int(p))


def itoa(i):
    return chr(97 + i - 1)

N = int(input())

ans = ""
while N:
    i = N % 26
    N = (N - 1) // 26
    ans += itoa(i)

print(ans[::-1])

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


import math
N = int(input())
char = [chr(i) for i in range(97, 97+26)]
K = math.floor(math.log(N , 26))
s = ''
mod = 26**K
for i in range(K+1):
  a = N//(mod)
  N = N % mod
  mod = int(mod/26)
  s += char[a-1]
print(s)


To_Acill = 96

N = int(input())

ans = []

jou26 = 1
while N > 0:
    tmp = N % (jou26*26)
    ans.append(chr(To_Acill + tmp//jou26))
    N = N-tmp
    jou26 = jou26*26

print("".join(reversed(ans)))


N=int(input())
s=""
while N>0:
    x=N%26
    if x==0:
        x=26
    N=N//26
    s=chr(96+x)+s
print(s)


Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


n = int(input())
a = list(map(int, input().strip().split()))
q = int(input())
bc = [map(int, input().split()) for _ in range(q)]
b, c = [list(i) for i in zip(*bc)]

for i in range(q):
    for aa in range(n):
        if(a[aa]==b[i]):
            a[aa]=c[i]
    print(sum(a))


import numpy as np
from numba import njit

def comb(n, r, p):
    r = min(r, n - r)
    ret = fac[n]
    ret = ret * facinv[r] % p
    return ret * facinv[n - r] % p

@njit
def comb_init(N_UNTIL, p):
    N_UNTIL += 1
    inv = np.empty(N_UNTIL, np.int64)
    fac = np.empty(N_UNTIL, np.int64)
    facinv = np.empty(N_UNTIL, np.int64)
    inv[0] = 0
    inv[1] = 1
    fac[0] = 1
    facinv[0] = 1
    for i in range(2, N_UNTIL):
        inv[i] = -inv[p % i] * (p // i) % p
    for i in range(1, N_UNTIL):
        fac[i] = fac[i - 1] * i % p
    for i in range(1, N_UNTIL):
        facinv[i] = facinv[i - 1] * inv[i] % p
    return inv, fac, facinv

K = int(input())
S = input()
N = len(S)
MOD = 1_000_000_007
inv, fac, facinv = comb_init(N + K - 1, MOD)
ans = 0
for i in range(K + 1):
    tmp = pow(25, K - i, MOD)
    tmp *= comb(N + K - i - 1, K - i, MOD)
    tmp %= MOD
    tmp *= pow(26, i, MOD)
    tmp %= MOD
    ans += tmp
    ans %= MOD
print(ans)

Score: 600 points

Problem Statement

How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?

The answer can be enormous, so print it modulo (10^9+7).

Constraints

K is an integer between 1 and 10^6 (inclusive).

S is a string of length between 1 and 10^6 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

K
S

Output

Print the number of strings satisfying the condition, modulo (10^9+7).

Sample Input 1

5
oof

Sample Output 1

575111451

For example, we can obtain proofend, moonwolf, and onionpuf, while we cannot obtain oofsix, oofelevennn, voxafolt, or fooooooo.

Sample Input 2

37564
whydidyoudesertme

Sample Output 2

318008117


Score : 200 points

Problem Statement

Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:

Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.

Constraints

1 \leq X \leq 179

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of times Takahashi will do the action before he is at the starting position again.

Sample Input 1

90

Sample Output 1

4

Takahashi's path is a square.

Sample Input 2

1

Sample Output 2

360


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

for i in range(5):
	if x[i] == 0:
    	print(i+1)

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


X, Y = map(int, input().split())
 ans = 'No'
 for a in range(X + 1):
 b = X - a
 if 2 * a + 4 * b == Y:
 ans = 'Yes'
 print(ans)

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


X,Y=map(int,input().split())
N=0
M=0
A=0
B=0
C=0
N=Y%2
if N==0:
    M=X*4
    if M>=Y:
        A=Y%X
        B=Y/X
        if A==0:
            if B>2:
                print("Yes")
            else:
                print("No")
        else:
            if A>=0.5:
                C=B+1
                if C>2:
                    print("Yes")
                else:
                    print("No")
            else:
                if B>2:
                    print("Yes")
                else:
                    print("No")
    else:
        print("No")
else:
    print("No")


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

for i in range(110):
    if X-i not in p:
        print(X-i)
        exit()
    if X+i not in p:
        print(X+i)
        exit()

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


def main():
    x, n = map(int, input().split())
    p = list(map(int, input().split()))
    _near = -1
    for i in range(-1, 102):
        if i in p:
            continue
        if abs(_near - x) > abs(i - x):
                _near = i
    print(_near)

if __name__ == "__main__":
    main()


def main():
  X, N = map(int, input().split())
  if N == 0:
    print(X)
    return
  p = tuple(map(int, input().split()))
  if X not in p:
    print(X)

  not_p = list(set([i for i in range(max(p)+2)]) - set(p))
  not_p_X = [abs(i - X) for i in not_p]
  print(not_p[not_p_X.index(min(not_p_X))])

main()


##C
X,N = map(int,input().split())
P = list(map(int,input().split()))
i=0

while X+i<=100:
    if X+i not in P:
        ans1 = X+i
        break
    i += 1
while X-i>=0:
    if X-i not in P:
        ans2 = X-i
        break
    i += 1
if ans1-X>=X-ans2:
    print(ans2)
else:
    print(ans1)


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

if n==0:
  print(x)

else:
  a = list(map(int,input().split()))
  if x not in a:
    print(x)
  else:
    for i in range(200):
      if x-i not in a:
        print(x-i)
        break
      if x+i not in a:
        print(x+i)
        break


Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


A, V = [int(n) for n in input().split()]
B, W = [int(n) for n in input().split()]
T = int(input())

if V <= W:
    print('NO')
    exit()

tmp = abs(B - A) // abs(V - W)

if B > A:
    va = [A + V * t for t in range(tmp, T+1)]
    vb = [B + W * t for t in range(tmp, T+1)]
else:
    va = [A - V * t for t in range(tmp, T+1)]
    vb = [B - W * t for t in range(tmp, T+1)]

va_vb_and = list(set(va) & set(vb))

if va_vb_and:
    print('YES')
    exit()
print('NO')

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

-10^9 \leq A,B \leq 10^9

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


a, v = map(int, input().split())
b, w = map(int, input().split())
t = int(input())
count = 0
for i in range(t+1):
    if v*i == abs(b - a) + w*i:
        count = 1
        break
    else:
        pass
print("Yes" if count == 1 else "No")


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

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


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


Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991


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

pool = []
for a,b in ab:
    af = sum([1 for a1,b1 in list(ab) if a1 <= a <= b1])
    bf = sum([1 for a1,b1 in list(ab) if a1 <= b <= b1])
    pool.append((a,af))
    pool.append((b, bf))

# print(pool)

max_pool = max([p[1] for p in pool])
pool = [p[0] for p in pool if p[1] >= max_pool-1]
# print(pool)

if max_pool%2 == 1:
    print(max(pool) - min(pool) + 1)
else:
    print(max(pool) - min(pool) + 1)


def main(sample_file = ''):

    """ convenient functions
    # for i, a in enumerate(iterable)
    # q, mod = divmod(a, b)
    # divmod(x, y) returns the tuple (x//y, x%y)
    # Higher-order function: reduce(operator.mul, xyz_count, 1)
    # manage median(s) using two heapq https://atcoder.jp/contests/abc127/tasks/abc127_f
    """

    """convenient decorator
    # @functools.lru_cache():
    # to facilitate use of recursive function
        # ex:
        # from functools import lru_cache
        # import sys
        # sys.setrecursionlimit(10**9)
        # @lru_cache(maxsize=None)
        # def fib(n):
        #     if n < 2:
        #         return n
        #     return fib(n-1) + fib(n-2)
        # print(fib(1000))
    """

    # import numpy as np
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product # https://docs.python.org/ja/3/library/itertools.html
    # accumulate() returns iterator! to get list: list(accumulate())
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor

        Args:
            n (long): number to be resolved into factors

        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  # prime factor
        b, e = 2, 0  # base, exponent
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.

        Args:
            n (long): number
            r (long): number

        Raises:
            Exception: not defined when n or r is negative

        Returns:
            long: number
        """
        # TODO: How should I do when n - r is negative?
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.

        Args:
            n (long): number
            r (long): number

        Raises:
            Exception: not defined when n or r is negative

        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict # https://docs.python.org/ja/3/library/collections.html#collections.deque
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest # https://docs.python.org/ja/3/library/heapq.html
    from copy import deepcopy, copy # https://docs.python.org/ja/3/library/copy.html
    import operator
    from operator import itemgetter #sort
    # ex1: List.sort(key=itemgetter(1))
    # ex2: sorted(tuples, key=itemgetter(1,2))
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]

        Args:
            x (long): current minimum value
            y (long): potential minimum value

        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]

        Args:
            x (long): current maximum value
            y (long): potential maximum value

        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd # Deprecated since version 3.5: Use math.gcd() instead.
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)
    def make_divisors(n, reversed=False):
        """create list of divisors

        Args:
            number (int): number from which list of divisors is created
            reversed (bool, optional): ascending order if False. Defaults to False.

        Returns:
            list: list of divisors
        """
        divisors = set()
        for i in range(1, int(n**0.5)+1):
            if n % i == 0:
                divisors.add(i)
                divisors.add(n//i)
        return sorted(list(divisors),reverse=reversed)

    # first create factorial_list
    # fac_list = mod_factorial_list(n)
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    AtoZ = list('abcdefghijklmnopqrsruvwxyz') # 26
    modpow = lambda a, n, p = MOD: pow(a, n, p) # Recursive function in python is slow!
    def modinv(a, p = MOD):
        # evaluate reciprocal using Fermat's little theorem:
        # a**(p-1) is identical to 1 (mod p) when a and p is coprime
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        # fac_list = modfactorial_list(100)
        # print(modcomb(100, 5, modfactorial_list(100)))
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N)
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)

        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x

        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root

            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx
                connected_num[rx] += connected_num[ry]

    class SegTree:
        """
        ref: https://qiita.com/takayg1/items/c811bd07c21923d7ec69
        init(init_val, ide_ele): 配列init_valで初期化 O(N)
        update(k, x): k番目の値をxに更新 O(logN)
        query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
        """
        def __init__(self, init_val, segfunc, ide_ele):
            """
            init_val: 配列の初期値
            segfunc: 区間にしたい操作
            ide_ele: 単位元
            n: 要素数
            num: n以上の最小の2のべき乗
            tree: セグメント木(1-index)
            """
            n = len(init_val)
            self.segfunc = segfunc
            self.ide_ele = ide_ele
            self.num = 1 << (n - 1).bit_length()
            self.tree = [ide_ele] * 2 * self.num
            # 配列の値を葉にセット
            for i in range(n):
                self.tree[self.num + i] = init_val[i]
            # 構築していく
            for i in range(self.num - 1, 0, -1):
                self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])

        def update(self, k, x):
            """
            k番目の値をxに更新
            k: index(0-index)
            x: update value
            """
            k += self.num
            self.tree[k] = x
            while k > 1:
                self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
                k >>= 1

        def query(self, l, r):
            """
            [l, r)のsegfuncしたものを得る
            l: index(0-index)
            r: index(0-index)
            """
            res = self.ide_ele
            l += self.num
            r += self.num
            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

    # ************ Graph ************
    # Graph: https://en.wikipedia.org/wiki/Directed_graph
    # 最短経路問題: https://ja.wikipedia.org/wiki/%E6%9C%80%E7%9F%AD%E7%B5%8C%E8%B7%AF%E5%95%8F%E9%A1%8C

    # Bellman-Ford: O(|V||E|). Use this if there exists an edge with negative length in the graph
    # After N steps, the shortest path has converded if there doesn't exist an cycle of edges with negative
    # Watch out: d[N] == d[2*N] doesn't necessarily mean the graph doesn't have negative cycle
    # ref: https://www.youtube.com/watch?v=1Z6ofKN03_Y

    def BellmanFord(N, M, ABC, vertex_start, vertex_end, value_if_inf = -1, find_shortest = False):
        """to calculate furthest or shortest length between vertex_start and vertex_end using BellmanFord algorithm

        Args:
            N (int): number of vertices
            M (int): number of edges
            ABC (list): [(ai, bi, ci) for _ in range(N)] where i-th edge is directed from vertex ai to vertex bi and the length is ci
            vertex_start (int): start vertex. usually use 0.
            vertex_end (int): end vertex. usually use N-1.
            value_if_inf (int or string as you like, optional): value you want when the furthest (or shortest) distance is infinite (or -infinite). Defaults to -1.
            find_shortest (bool, optional): choose False to find furthest path. Defaults to False.

        Returns:
            int or string: normally int (but can be str if you set value_if_inf to str)

        Example:
                N, M, P = R()
                ABC = [R() for _ in range(M)]
                ABC = [(a-1, b-1, c-P) for a, b, c in ABC]
                print(BellmanFord(N, M, ABC, 0, N-1, value_if_inf = 'inf'))

        """

        def make_reachable_list(N, M, ABC, vertex_start, vertex_end):
            reachable_to_direct = defaultdict(list)
            reachable_from_direct = defaultdict(list)
            reachable_from_start = [False] * N
            reachable_to_end = [False] * N
            reachable_from_start[vertex_start] = True
            reachable_to_end[vertex_end] = True
            reachable_from_both_sides = [False] * N
            dfs_from_start = []
            dfs_to_end = []
            for a, b, c in ABC:
                reachable_to_direct[a].append(b)
                reachable_from_direct[b].append(a)
                if a == vertex_start:
                    dfs_from_start.append(b)
                    reachable_from_start[b] = True
                if b == vertex_end:
                    dfs_to_end.append(a)
                    reachable_to_end[a] = True
            while dfs_from_start:
                v = dfs_from_start.pop()
                for i in reachable_to_direct[v]:
                    if not reachable_from_start[i]:
                        reachable_from_start[i] = True
                        dfs_from_start.append(i)
            while dfs_to_end:
                v = dfs_to_end.pop()
                for i in reachable_from_direct[v]:
                    if not reachable_to_end[i]:
                        reachable_to_end[i] = True
                        dfs_to_end.append(i)
            for i in range(N):
                reachable_from_both_sides[i] = reachable_from_start[i] and reachable_to_end[i]
            return reachable_from_both_sides

        reachable_from_both_sides = make_reachable_list(N, M, ABC, vertex_start, vertex_end)

        if find_shortest:
            dist = [INF for i in range(N)]
        else:
            dist = [-INF for i in range(N)]

        dist[vertex_start] = 0
        for i in range(N):
            updated = False
            for a, b, c in ABC:
                if not reachable_from_both_sides[a]:
                    continue
                elif find_shortest:
                    update_condition = dist[a] + c < dist[b]
                else:
                    update_condition = dist[a] + c > dist[b]
                if dist[a] != INF and update_condition:
                    dist[b] = dist[a] + c
                    updated = True
                    if i == N-1:
                        return value_if_inf
            if not updated:
                break
        return dist[vertex_end]

    # Warshall Floyd O(V**3)
    def warshall_floyd(number_vertex, XYD, shift_one_for_vertex=False):
        # ref: https://juppy.hatenablog.com/entry/2018/11/01/%E8%9F%BB%E6%9C%AC_python_%E5%85%A8%E7%82%B9%E5%AF%BE%E6%9C%80%E7%9F%AD%E7%B5%8C%E8%B7%AF%E6%B3%95%EF%BC%88%E3%83%AF%E3%83%BC%E3%82%B7%E3%83%A3%E3%83%AB%E3%83%95%E3%83%AD%E3%82%A4%E3%83%89%E6%B3%95
        # number_vertex: len(vertex)
        # XYD: list of distance from x to y
        # shift_one_for_vertex: XYDの値が1~Nの時(0~N-1でない時)に調整するフラグ。
        # d[i][j]: iからjへの最短距離
        d = [[float("inf")]*number_vertex for i in range(number_vertex)]
        for x, y, dist in XYD:
            if shift_one_for_vertex:
                x = x - 1
                y = y - 1
            d[x][y] = dist
            d[y][x] = dist
        for i in range(number_vertex):
            d[i][i] = 0 # distance of same vertex is 0
        for k in range(number_vertex):
            for i in range(number_vertex):
                for j in range(number_vertex):
                    d[i][j] = min(d[i][j],d[i][k] + d[k][j])
        return d

    """ initialize variables and set inputs
    # initialize variables
        # to initialize list, use [0] * n
        # to initialize two dimentional array:
            # ex) [[0] * N for _ in range(N)]
            # ex2) dp = [[0] * (N+1) for _ in range(W*2)]
    # set inputs
        # put inputs between specific values (almost as quickly)
        # ex) S = [-INF] + [int(r()) for _ in range(A)] + [INF]
        # open(0).read() is sometimes useful:
        # ex) n, m, *x = map(int, open(0).read().split())
        #     min(x[::2]) - max(x[1::2])
        # ex2) *x, = map(int, open(0).read().split())
        #     don't forget to add comma after *x if only one variable is used
    # preprocessing
        # transpose = [x for x in zip(*data)]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
        # flat = [flatten for inner in data for flatten in inner]
        # ex) [[1, 2, 3], [4, 5, 6], [7, 8, 9]] => [1, 2, 3, 4, 5, 6, 7, 8, 9]
    # calculate and output
        # output pattern
        # ex1) print(*l) => when l = [2, 5, 6], printed 2 5 6
    """

    # functions to read input
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    r_float = lambda: float(r())
    R = lambda: list(map(int, r().split()))
    R_str = lambda: r().split()
    R_map = lambda: map(int, r().split())
    R_float = lambda: list(map(float, r().split()))
    R_tuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    # single int: int(r())
    # single string: r()
    # single float: float(r())
    # line int: R()
    # line string: r().split()
    # line (str, int, int): [j if i == 0 else int(j) for i, j in enumerate(r().split())]
    # lines int: [R() for _ in range(n)]
    """

    # for test
    if sample_file:
        sys.stdin = open(sample_file)

    # ----------------------------------
    # main
    #%%
    N = r_int()
    AB = [R() for _ in range(N)]

    ab_0 = sorted(AB, key=itemgetter(0))
    ab_1 = sorted(AB, key=itemgetter(1))

    if N%2 == 0: # 偶数の時
        left = N//2 - 1
        right = N//2
        l = ab_0[left][0] + ab_0[right][0]
        r = ab_1[left][1] + ab_1[right][1]
        print(r-l+1)
    else:
        c = N//2
        l = ab_0[c][0]
        r = ab_1[c][1]
        print(r-l+1)

    #%%
    # end of main
    # ----------------------------------

    """memo: how to use defaultdict of list
    # initialize
    Dic = defaultdict(list)
    # append / extend
    Dic[x].append(y)
    # three methods for loop: keys(), values(), items()
    for k, v in Dic.items():
    """

    """memo: how to solve binary problems
    # to make binary digits text
    >>> a = 5
    >>> bin_str_a = format(a, '#06b')
    >>> print(bin_str_a)
    0b0101 # first 2 strings (='0b') indicates it is binary
    """

    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

if __name__ == '__main__':
    main()


from statistics import median

N = int(input())
As = [0] * N
Bs = [0] * N

for i in range(N):
    As[i], Bs[i] = map(int, input().split())

med_A = median(As)
med_B = median(Bs)

if N%2:
    print(med_B-med_A+1)
else:
    print(int((med_B-med_A)*2)+1)


print(''.join(['D' if c == '?' else c for c in input()]))

Score : 200 points

Problem Statement

For a string S consisting of the uppercase English letters P and D, let the doctoral and postdoctoral quotient of S be the total number of occurrences of D and PD in S as contiguous substrings. For example, if S = PPDDP, it contains two occurrences of D and one occurrence of PD as contiguous substrings, so the doctoral and postdoctoral quotient of S is 3.

We have a string T consisting of P, D, and ?.

Among the strings that can be obtained by replacing each ? in T with P or D, find one with the maximum possible doctoral and postdoctoral quotient.

Constraints

1 \leq |T| \leq 2 \times 10^5

T consists of P, D, and ?.

Input

Input is given from Standard Input in the following format:

T

Output

Print one string with the maximum possible doctoral and postdoctoral quotient among the strings that can be obtained by replacing each ? in T with P or D.
If there are multiple such strings, you may print any of them.

Sample Input 1

PD?D??P

Sample Output 1

PDPDPDP

This string contains three occurrences of D and three occurrences of PD as contiguous substrings, so its doctoral and postdoctoral quotient is 6, which is the maximum doctoral and postdoctoral quotient of a string obtained by replacing each ? in T with P or D.

Sample Input 2

P?P?

Sample Output 2

PDPD


import math

n = int(input())
folia = list(map(int, input().split()))
#print(n, folia)

seq = [[folia[-1], folia[-1]]]

for i in range(n): # 深さ'n'分
    tmp = folia[-(i+2)]
    sml = math.ceil(seq[i][0] / 2) + tmp
    big = seq[i][1] + tmp
    seq += [[sml, big]]
#print(seq)

if not (seq[-1][0] <= 1 <= seq[-1][1]):
    print(-1)
    exit()

ans =[1]
for j in range(n): # 深さ'n'分
    tmp = min((ans[j] - folia[j]) * 2, seq[-(j+2)][1])
    ans.append(tmp)
print(sum(ans))

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


#C
N=int(input())
A=[int(x) for x in input().split()]

P=[0 for i in range(N+1)]
P[N]=[A[N],A[N]]
for i in range(N-1,-1,-1):
    MIN,MAX=P[i+1]
    mi=int(A[i]+(MIN+MIN%2)/2)
    ma=A[i]+MAX
    P[i]=[mi,ma]

if P[0][0]==1:
    Q=[0 for i in range(N+1)]
    Q[0]=1
    cnt=1
    for i in range(N):
        Q[i+1]=min((Q[i]-A[i])*2,P[i+1][1])
        cnt+=Q[i+1]
    print(cnt)
else:
    print("-1")


from sys import stdin, stdout
n = int(stdin.readline())
nmleaves = list(map(int, stdin.readline().strip().split()))

# pref[i]: sum of all elements in nmleaves after i, i.e. sum(nmleaves[i+1:])
full = sum(nmleaves)
tot = 0
pref = [0]*(n+1)
for i, l in enumerate(nmleaves):
    tot += l
    pref[i] = full - tot

if n==0:
    print(0)

else:
    if nmleaves[0]!=0:
        print(-1)
        exit()

    ## it exists
    ans = 0
    for level, leaves in enumerate(nmleaves):
        if leaves > 2**(level):
            print(-1)
            exit()

        if level == 0:
            ans += 1
            validnom = 1
        else:
            maxup = 2*validnom
            maxnom = maxup - leaves

            if level+1<len(nmleaves):
                validnom = min(maxnom, pref[level], 2**level)
                ans += (leaves + validnom)
            else:
                ans += leaves
    print(ans)


costs = {}
searching = {}

def init(a, b, c, d):
    my_costs = {}
    my_costs[0] = 0
    frontier = set([0])
    for depth in range(8):
        new_frontier = set()
        for f in frontier:
            for ff, cst in [(f*2, a), (f*3, b), (f*5, c), (f-1, d), (f+1, d)]:
                if ff < 0:
                    continue
                if ff not in my_costs:
                    my_costs[ff] = my_costs[f] + cst
                else:
                    my_costs[ff] = min(my_costs[f] + cst, my_costs[ff])
                new_frontier.add(ff)
        frontier = new_frontier
    for k in range(20):
        costs[k] = my_costs[k]

def solve(n, a, b, c, d):
    if n in costs:
        return costs[n]

    next_step = {}
    for delta in range(-5, 5+1):
        m = n + delta
        for div, div_cost in [(2, a), (3, b), (5, c)]:
            if m % div == 0:
                cst = d * abs(delta) + div_cost
                r = m // div
                if r not in next_step:
                    next_step[r] = cst
                else:
                    next_step[r] = min(next_step[r], cst)

    #print(f'next step for {n} is {list(next_step.keys())}')
    costs_lst = []
    for r in next_step:
        cst = solve(r, a, b, c, d) + next_step[r]
        costs_lst.append(cst)
    costs[n] = min(costs_lst + [n*d])
    return costs[n]

t = int(input())

for casenum in range(1, t+1):
    n, a, b, c, d = map(int, input().split())
    costs = {}
    searching = {}

    init(a, b, c, d)
    answer = solve(n, a, b, c, d)
    #print(f'answer for {n, a, b, c, d} = {answer}')
    print(answer)

Score : 400 points

Problem Statement

You start with the number 0 and you want to reach the number N.

You can change the number, paying a certain amount of coins, with the following operations:

Multiply the number by 2, paying A coins.

Multiply the number by 3, paying B coins.

Multiply the number by 5, paying C coins.

Increase or decrease the number by 1, paying D coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach N?

You have to solve T testcases.

Constraints

1 \le T \le 10

1 \le N \le 10^{18}

1 \le A, B, C, D \le 10^9

All numbers N, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

T

Then, T lines follow describing the T testcases.
Each of the T lines has the format

N A B C D

Output

For each testcase, print the answer on Standard Output followed by a newline.

Sample Input 1

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321

Sample Output 1

20
19
26
3821859835
23441258666

For the first testcase, a sequence of moves that achieves the minimum cost of 20 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 1 to multiply by 2 (x = 4).

Pay 2 to multiply by 3 (x = 12).

Pay 8 to decrease by 1 (x = 11).

For the second testcase, a sequence of moves that achieves the minimum cost of 19 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 2 to multiply by 5 (x = 10).

Pay 8 to increase by 1 (x = 11).


N = int(input())
N %= 10
ans = 0
if N == 3:
    ans = 'bon'
elif N in [0,1,6,8]:
    ans = 'pon'
else:
    ans = 'hon'
print(ans)

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


N = int(input()) %10
hon=[2,4,5,7,9]
bon=[3]

if N in hon:
    print("hon")
elif N in bon:
    print("bon")
else:
    print("pon")


n = input()
m = int(n[-1])
hon = ['pon', 'pon', 'hon', 'bon', 'hon', 'hon', 'pon', 'hon', 'pon', 'hon']
print(hon[m])


N=list(int(input()))
if N[-1]==0 or N[-1]==1 or N[-1]==6 or N[-1]==8:
  print("pon")
elif N[-1]==3:
  print("bon")
else:
  print("hon")


N=int(input())
S=list(input())
if len(S)<=N:
   for i in range(len(S)):
       print(S[i],end="")
else:
    for i in range(N):
        print(S[i],end="")

Score: 200 points

Problem Statement

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

Constraints

K is an integer between 1 and 100 (inclusive).

S is a string consisting of lowercase English letters.

The length of S is between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

K
S

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.

We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


K = int(input())
S = input()

s_l = len(S)
if s_l > K:
  print(S[0:K] + "...")
else:
  print(S)


K = int(input())
S = input()

length = len(S)

if length <= K:
	print(S)
else:
	res = S[:K]
	print( res + "...")


K = int(input())
S = input()

print( S if K >= len(S) else S[:K] + "...")


import sys
input = sys.stdin.readline
import math
def main():
    A, B, H, M = map(int, input().split())
    s_rad = 0
    if H == 0:
        s_rad = math.pi/2
    elif H <= 3:
        s_rad = (3-H)/12*2*math.pi
    else:
        s_rad = math.pi/2 + (12-H)/12*2*math.pi
    l_rad = 0
    if M == 0:
        l_rad = math.pi/2
    elif M <= 15:
        l_rad = (15-M)/60*2*math.pi
    else:
        l_rad = math.pi/2 + (60-M)/60*2*math.pi
    sx = A * math.cos(s_rad)
    sy = A * math.sin(s_rad)
    lx = B * math.cos(l_rad)
    ly = B * math.sin(l_rad)
    ans = math.sqrt(((sx-lx)**2) + ((sy-ly)**2))
    print(ans)
if __name__ == "__main__":
    main()

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


# -*- coding: utf-8 -*-
import math
from decimal import Decimal
# 入力
a,b,h,m = map(int,input().split())

tri_m = Decimal(360 / 60 * m )

tri_h = Decimal((360 / 12 * h) + (360 / 12 / 60 * m))

# print("tri_m:{},tri_h:{}".format(tri_m,tri_h))
angle = Decimal(abs(tri_m - tri_h))
if angle > 180:
  angle -= 180

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

ans = Decimal(math.sqrt(a**2 + b**2 - 2 * a * b * math.cos(math.radians(angle))))

print(ans)


import math
A,B,H,M =  (int(x) for x in input().split())
h = 360*H/12 + 30*M/60
m = 360*M/60
c = abs(h-m)
if(c > 180):
    c = 360 - c
C = A**2 + B**2 - 2*A*B*math.cos(math.radians(c))
if c != 180 and c != 0:
    print(math.sqrt(C))
elif c == 180:
    print(A+B)
else:
    print(abs(A-B))


from collections import deque
N,M = map(int, input().split())
AB_s = [list(map(int, input().split())) for _ in range(M)]

MAP = [[] for _ in range(N)]
for AB in AB_s:
    A, B = map(int, AB)
    MAP[A-1].append(B)
    MAP[B-1].append(A)
answer = [0] * N
queue = deque([1])
answer[0] = N
while len(queue) > 0:
    P = queue.popleft()
    if True:
        for Q in MAP[P-1]:
            if answer[Q-1] == 0:
                answer[Q-1] = P
                queue.append(Q)
if min(answer) == 0:
    print("No")
else:
    print("Yes")
    for i in range(1,N):
        print(answer[i])

Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 2 \times 10^5

1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

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

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.


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

graph = [[] for _ in range(N)]
for i, (Ai, Bi) in enumerate(AB):
    graph[Ai - 1].append(Bi - 1)
    graph[Bi - 1].append(Ai - 1)

import heapq

MY_INF = 1000000007
q = [(0, 0)]
d = [MY_INF] * N
d[0] = 0
while len(q) > 0:
    dist, src = heapq.heappop(q)
    for dst in graph[src]:
        dist_tmp = dist + 1
        if d[dst] > dist_tmp:
            d[dst] = dist_tmp
            heapq.heappush(q, (dist_tmp, dst))

for src in range(N):
    if src == 0:
        print('Yes')
        continue
    #
    dist_min = MY_INF
    ans = 0
    for dst in graph[src]:
        if dist_min > d[dst]:
            dist_min = d[dst]
            ans = dst + 1
    #
    print(ans)


from collections import defaultdict
from math import gcd

n = int(input())
L = []
for i in range(n):
    l = list(map(int, input().split()))
    L.append(l)

Mod = 10 ** 9 + 7

Pow2 = [1]
for i in range(n):
    Pow2.append(Pow2[-1] * 2 % Mod)

def kikaku(a, b):
    g = gcd(a, b)
    a //= g
    b //= g
    if a < 0:
        return - a, -b
    return a, b

Dpos = defaultdict(int)
Dneg = defaultdict(int)

c = 0
for l in L:
    a = l[0]
    b = l[1]
    if a == b == 0:
        c += 1
    else:
        a, b = kikaku(a, b)
        if b > 0:
            Dpos[(b, -a)] += 1
            Dneg[(b, -a)] += 0
        else:
            Dpos[(a, b)] += 0
            Dneg[(a, b)] += 1

r = 1
for k, v in Dpos.items():
    j = Dneg[k]
    x = Pow2[v] + Pow2[j] - 1
    r = r * x % Mod
ans = (r + c - 1) % Mod
print(ans)

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

10
3 2
3 2
-1 1
2 -1
-3 -9
-8 12
7 7
8 1
8 2
8 4

Sample Output 2

479


s = input()
t = input()
t_new = t[:-1]

if s == t_new :
  print('Yes')
else :
  print('No')

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


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

# 文字列の入力
S = input()
T = input()

judge = "NO"

if (len(S) + 1 == len(T)):
    if (T.startswith(S)):
        judge = "YES"

print("{}".format(judge))


def s0():return input()
def s1():return input().split()
def s2(n):return [input() for x in range(n)]
def s3(n):return [[input().split()] for _ in range(n)]
def n0():return int(input())
def n1():return [int(x) for x in input().split()]
def n2(n):return [int(input()) for _ in range(n)]
def n3(n):return [[int(x) for x in input().split()] for _ in range(n)]

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


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

s = 0
if k <= a:
    print(k)
elif k <= a+b:
    print(a)
else:
    print(a-(k-a-b))

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000