import math
import sys

#素数か(x>=2)
def prime_check(x): #x>=2
    if x==2:
        return True,2
    elif x%2==0:
        return False,2
    else:
        limit=int(math.sqrt(x))
        for factor in range(3,limit+1,2):
            if x%factor==0:
                return False,factor
        return True,x

#素因数分解(x>=2)
def prime_factorization(x): #x>=2
    factor_dictionary={}
    factor_set=set()
    judge,factor=prime_check(x)
    while True:
        if factor in factor_set:
            factor_dictionary[factor]+=1
        else:
            factor_dictionary[factor]=1
            factor_set.add(factor)

        if judge:
            return factor_dictionary,factor_set
            break
        else:
            x//=factor
            judge,factor=prime_check(x)

n=int(input())
Fd,Fs=prime_factorization(n)

def culc(x):
    temp=1
    while True:
        if x>=temp:
            x-=temp
            temp+=1
        else:
            return temp-1
            break

if n==1:
    print(0)
    sys.exit()

ans=0
while Fs:
    now=Fs.pop()
    ans+=culc(Fd[now])

print(ans)


import math

N = int(input())
A = []
B = []
for i in range(N):
    in1, in2 = list(map(int,input().split()))
    A.append(in1)
    B.append(in2)
AA = sorted(A)
BB = sorted(B)

if N%2==1:
    low = AA[N//2  ]
    high = BB[N//2  ]
    print(high - low +1)

else:
    low = (AA[N//2-1] + AA[N//2]) / 2
    high = (BB[N//2-1] + BB[N//2]) / 2
    count=0
    while True:
        low = low+ 0.5*count
        count+=1
        if low>high:
            break
    #low = math.floor(low)
    #high = math.ceil(high)
    print(count)

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

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

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.


#F
N,S=map(int,input().split())
A=list(map(int,input().split()))
mod=998244353

dp=[[0 for j in range(S+1)] for i in range(N+1)]
dp[0][0]+=1
for i in range(N):
    for j in range(S+1):
        dp[i+1][j]+=2*dp[i][j]
        dp[i+1][j]%=mod
        if j+A[i]<=S:
            dp[i+1][j+A[i]]+=dp[i][j]
            dp[i+1][j+A[i]]%=mod
print(dp[N][S])

Score : 600 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N and another positive integer S.

For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:

f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(T) modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

6

For each T, the value of f(T) is shown below. The sum of these values is 6.

f(\{1\}) = 0

f(\{2\}) = 0

f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)

f(\{1, 2\}) = 1 (\{1, 2\})

f(\{2, 3\}) = 1 (\{3\})

f(\{1, 3\}) = 1 (\{3\})

f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

3296


T = input() #ここで標準入力

trade = T.replace('?','D')
print(trade)

Score : 100 points

Problem Statement

In this problem, we use the 24-hour clock.

Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.)
He has decided to study for K consecutive minutes while he is up.
What is the length of the period in which he can start studying?

Constraints

0 \le H_1, H_2 \le 23

0 \le M_1, M_2 \le 59

The time H_1 : M_1 comes before the time H_2 : M_2.

K \ge 1

Takahashi is up for at least K minutes.

All values in input are integers (without leading zeros).

Input

Input is given from Standard Input in the following format:

H_1 M_1 H_2 M_2 K

Output

Print the length of the period in which he can start studying, as an integer.

Sample Input 1

10 0 15 0 30

Sample Output 1

270

Takahashi gets up at exactly ten in the morning and goes to bed at exactly three in the afternoon.
It takes 30 minutes to do the study, so he can start it in the period between ten o'clock and half-past two. The length of this period is 270 minutes, so we should print 270.

Sample Input 2

10 0 12 0 120

Sample Output 2

0

Takahashi gets up at exactly ten in the morning and goes to bed at exactly noon. It takes 120 minutes to do the study, so he has to start it at exactly ten o'clock. Thus, we should print 0.


import sys
input = sys.stdin.readline
from functools import lru_cache

T=int(input())
for tests in range(T):
    N,A,B,C,D=map(int,input().split())

    DP=[N*D]*(10**5)
    DP[0]=0

    for i in range(10**5):
        for k in range(i-10,i+10):
            if 0<=k<10**5 and DP[k]>DP[i]+abs(i-k)*D:
                DP[k]=DP[i]+abs(i-k)*D
        #if 0<=i+1<10**5 and DP[i+1]>DP[i]+D:
        #    DP[i+1]=DP[i]+D

        #if 0<=i-1<10**5 and DP[i-1]>DP[i]+D:
        #    DP[i-1]=DP[i]+D

        if 0<=2*i<10**5 and DP[2*i]>DP[i]+A:
            DP[2*i]=DP[i]+A

        if 0<=3*i<10**5 and DP[3*i]>DP[i]+B:
            DP[3*i]=DP[i]+B

        if 0<=5*i<10**5 and DP[5*i]>DP[i]+C:
            DP[5*i]=DP[i]+C

    @lru_cache(maxsize=None)
    def calc(x):
        if x<=10:
            return DP[x]

        ANS=x*D

        two=x//2*2

        ANS=min(ANS,abs(two-x)*D+A+calc(two//2))
        ANS=min(ANS,abs(two+2-x)*D+A+calc(two//2+1))

        three=x//3*3
        ANS=min(ANS,abs(three-x)*D+B+calc(three//3))
        ANS=min(ANS,abs(three+3-x)*D+B+calc(three//3+1))

        five=x//5*5
        ANS=min(ANS,abs(five-x)*D+C+calc(five//5))
        ANS=min(ANS,abs(five+5-x)*D+C+calc(five//5+1))

        return ANS

    print(calc(N))

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).


# Inputing values

t=int(input())

# for loop

for i in range(t):
    n,a,b,c,d=map(int,input().split())
n,A,B,C=map(int,input().split())

# new vars

l=[int(input()) for _ in range(n)]

# defineing new

def dfs(count,a,b,c):

  # if-else looping
    if count==n:
        if min(a,b,c)>0:
            return abs(a-A)+abs(b-B)+abs(c-C)-30
        else:
            return 10**9+1

          # new vars

    x = dfs(count+1, a, b, c)
    y = dfs(count+1, a+l[count], b, c)+10
    z = dfs(count+1, a, b+l[count], c)+10
    w = dfs(count+1, a, b, c+l[count])+10
    return min(x,y,z,w)

# printing answer

print(dfs(0,0,0,0))


N=int(input())
if N%10==3:
    print("bon")
elif N%10==0:
    print("pon")
elif N%10==1:
    print("pon")
elif N%10==6:
    print("pon")
elif N%10==8:
    print("pon")
else:
    print("hon")

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


k =int(input())
s =input()
ans = ''
if k>len(s):
  k = len(s)
for i in range (k):
  ans = ans+s[i]

if k<len(s):
  print(ans+'...')
else:
  print(ans)

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

if len(S) <= K:
    print(S)
else:
    print(S[0:K] + '...')


K = int(input())
S = input()
if len(S) > K:
    print(S[:K] + '...')
else:
    print(S)


import sys
K = int(input())
S = input()

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


K = int(input())
S = list(input())
if len(S) > K:
    print(''.join(S[:K]) + '...')
else:
    print(''.join(S))


k=int(input())
s=input()
if len(s)<=k:
    print(s)
else:
    print(s[:k]+'...')


def main():
    #
    K = int(input())
    S = input()
    # S = list(map(int, input().split(' ')))
    # print(S, W)

    # if :
    #     print('')
    # else:
    #     print('')

    len_s = len(S)

    if len_s <= K:
        print(S)
    else:
        a = S[0:K] + '...'
        print(a)

main()


import math
A,B,H,M = map(int, input().split())
rate = M / 60
HM = H*5 + 5*rate
theta = abs(HM-M) * 6
if theta > 180:
    theta = 360-theta
rad = math.radians(theta)
cos = (math.cos(rad))
L = math.sqrt(A*A + B*B - 2*A*B*cos)
print("{:.19f}".format(L))

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.


import math
a,b,c,d=input().split()
a=float(a)
b=float(b)
c=float(c)
d=float(d)
sa=30*c-5.5*d
if sa<0.000:
    sa=float(6*d-(30*c+0.5*d))
if sa>180.000:
    sa=sa-180
    sa=float(sa)
x=math.sqrt(a*a+b*b-2*a*b*float((math.cos(math.radians(sa)))))
print(x)


import math
import numpy

a,b,h,m=map(int,input().split())
k=30*h+int(m/2)
n=6*m
tmp = n - k
tmp = math.radians(tmp)
tmp = math.cos(tmp)

ans = a**2+b**2-2*a*b*tmp
ans = numpy.sqrt(ans)
print(str(ans))


"""    Arnab Chanda    """

from collections import defaultdict, deque
from itertools import permutations
from sys import stdin,stdout
from bisect import bisect_left, bisect_right
from copy import deepcopy
import heapq

from math import sqrt,cos, pi

int_input=lambda : int(stdin.readline())
string_input=lambda : stdin.readline().split()
multi_int_input =lambda : map(int, stdin.readline().split())
multi_input = lambda : stdin.readline().split()
list_input=lambda : list(map(int,stdin.readline().split()))
string_list_input=lambda: list(string_input())
MOD = pow(10,9)+7

def calcAngle(h,m):

        if (h == 12):
            h = 0
        if (m == 60):
            m = 0

        # Calculate the angles moved by
        # hour and minute hands with
        # reference to 12:00
        hour_angle = 0.5 * (h * 60 + m)
        minute_angle = 6 * m

        # Find the difference between two angles
        angle = abs(hour_angle - minute_angle)

        # Return the smaller angle of two
        # possible angles
        angle = min(360 - angle, angle)

        return angle

a,b, h, m = multi_int_input()

angle = calcAngle(h, m)*(pi/180)
# angle = calcAngle(h, m)
# print(angle)

print(sqrt( a*a + b*b - 2*a*b*cos(angle)))


#!/usr/bin/env python
from collections import deque

def main():
    n, m = map(int, input().split())
    rw_lst = [[] for _ in range(n+1)]
    for _ in range(m):
        a, b = map(int, input().split())
        rw_lst[a].append(b)
        rw_lst[b].append(a)

    sign_lst = [-1 for _ in range(n+1)]
    sign_lst[1] = 0
    check_lst = [False for _ in range(n+1)]
    check_lst[1] = True

    queue = deque([1])
    while queue:
        room = queue.popleft()
        for way in rw_lst[room]:
            if not check_lst[way]:
                check_lst[way] = True
                sign_lst[way] = room
                queue.append(way)

    check = True
    for i in range(1, n+1):
        check = check and check_lst[i]

    if check:
        print("Yes")
        for i in range(2, n+1):
            print(sign_lst[i])
    else:
        print("No")

if __name__ == '__main__':
    main()

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.


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

ans = 0

if a >= k:
  ans = k
  k = 0
else:
  ans = a
  k -= a
if b >= k:
  k = 0
else:
  k -= b
ans -= k

print(ans)

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


A, B, C, K = map(int, input().split())

def f():
    if K <= A:
        return K
    elif K <= A + B:
        return A
    else:
        #1が書かれたカードの枚数 - -1が書かれたカードの枚数（）
        return A - (K - A - B)

print(f())


a, b, c, k = [int(x) for x in input().split()]

ans = min(a, k)
k -= a
k -= b
ans -= k if k > 0 else 0

print(ans)


a, b, c, k = [int(i) for i in input().split()]
ans = 0
if a > k:
    ans += k
    print(ans)
    exit()

ans += a
k -= a
if k < 0:
    print(ans)
    exit()

k -= b
if k < 0:
    print(ans)
    exit()

ans += (-1*k)
print(ans)


def resolve():
    import sys

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

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

    arr = [1] * a + [0] * b + [-1] * c

    print(sum(arr[0:k]))

resolve()


import itertools

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

for a in range(1, N + 1):
  for c in itertools.combinations(CA, a):
    C.append(list(c))

p = float('inf')

for c in C:
  tp = float('inf')
  t = [0] * (M + 1)
  for con in c:
    for i in range(M + 1):
      t[i] += con[i]
      flg = True
    for i in range(1, M + 1):
      if t[i] < X: flg = False
    if flg: p = min(p, t[0])

if p == float('inf'):
  print(-1)
else:
  print(p)

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

3 3 10
100 3 1 4
100 1 5 9
100 2 6 5

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067


import math
import sys
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from functools import lru_cache, reduce
from heapq import heapify, heappop, heappush
from itertools import chain, combinations, permutations, product
from typing import List, Dict

# import numpy as np

sys.setrecursionlimit(10**6 + 1)
input = sys.stdin.readline
write = sys.stdout.write

def read_item(cls=int):
    return cls(input())

def read_n_item(cls=int) -> list:
    return [cls(s) for s in input().split()]

def list2d(row, col, init_val=0) -> List[list]:
    return [[init_val] * col for _ in range(row)]

MOD = 10**9 + 7

n, m, x = map(int, input().split())
prices = []
mat = []
for _ in range(n):
    nums = read_n_item()
    prices.append(nums[0])
    mat.append(nums[1:])

def check(nums):
    for num in nums:
        if num < x:
            return False
    return True

def dfs(cur, pos, price, min_price):
    if check(cur):
        min_price = min(price, min_price)
        return min_price
    if pos == n:
        return min_price

    min_price = min(dfs(cur, pos+1, price, min_price), min_price)

    nxt = [0] * len(cur)
    for i in range(len(cur)):
        nxt[i] = cur[i] + mat[pos][i]
    min_price = min(min_price, dfs(nxt, pos+1, price+prices[pos], min_price))
    return min_price

min_price = dfs([0]*m, 0, 0, float('inf'))

if min_price == float('inf'):
    print(-1)
else:
    print(min_price)


import sys

try:
    sys.stdin = open(sys.path[0] + '\\input.txt', 'r')
    sys.stdout = open(sys.path[0] + '\\output.txt', 'w')
except FileNotFoundError:
    pass

n, m, x = list(map(int, input().split()))
arr = []
c = []

for i in range(n):
    row = list(map(int, input().split()))
    c.append(row[0])
    arr.append(row[1:])

mincost = float('inf')

for i in range(1 << n):
    temp = []
    cost = 0

    for j in range(n):
        if i & (1 << j):
            temp.append(j)
            cost += c[j]

    if temp:
        res = [0] * m
        for k in temp:
            for i in range(m):
                res[i] += arr[k][i]

        flag = True
        for i in res:
            if i < x:
                flag = False
                break

        if flag:
            mincost = min(mincost, cost)

if mincost == float('inf'):
    print(-1)
else:
    print(mincost)


#!/usr/bin/env python3
import itertools

def main():
    N, M, X = map(int, input().split())
    C = [0] * N
    A = []
    for n in range(0, N):
        l = input().split()
        C[n] = int(l[0])
        A.append([int(i) for i in l[1:]])

    min_cost = sum(C) + 1
    for i in range(N):
        for comb in itertools.combinations(range(N), i):
            canAchive = True
            for m in range(M):
                r = 0
                for n in comb:
                    r += A[n][m]
                if (r < X):
                    canAchive = False
                    break
            if (canAchive):
                cost = sum([C[n] for n in comb])
                min_cost = min(min_cost, cost)

    if (min_cost <= sum(C)):
        print(min_cost)
    else:
        print(-1)

if __name__ == '__main__':
    main()


import sys
import itertools
import numpy as np

MOD = 998244353
MAX = 10 ** 5 * 2 + 5

fac = [0 for i in range(MAX)]
finv = [0 for i in range(MAX)]
inv = [0 for i in range(MAX)]

def comInit(mod):
    fac[0], fac[1] = 1, 1
    finv[0], finv[1] = 1, 1
    inv[1] = 1
    for i in range(2, MAX):
        fac[i] = fac[i - 1] * i % mod
        inv[i] = mod - inv[mod % i] * (mod // i) % mod
        finv[i] = finv[i - 1] * inv[i] % mod

def com(n, r, mod):
    if n < r:
        return 0
    if n < 0 or r < 0:
        return 0
    return fac[n] * (finv[r] * finv[n - r] % mod) % mod

comInit(MOD)

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

n, m, k = map(int, readline().split())

ans = 0
for x in range(k, -1, -1):
    # now *= (m - 1) % MOD
    ans += com(n - 1, x, MOD) % MOD
    # ans += tmp
print(ans % MOD)

Score : 500 points

Problem Statement

There are N blocks arranged in a row. Let us paint these blocks.

We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways.

Find the number of ways to paint the blocks under the following conditions:

For each block, use one of the M colors, Color 1 through Color M, to paint it. It is not mandatory to use all the colors.

There may be at most K pairs of adjacent blocks that are painted in the same color.

Since the count may be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

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

0 \leq K \leq N - 1

Input

Input is given from Standard Input in the following format:

N M K

Output

Print the answer.

Sample Input 1

3 2 1

Sample Output 1

6

The following ways to paint the blocks satisfy the conditions: 112, 121, 122, 211, 212, and 221. Here, digits represent the colors of the blocks.

Sample Input 2

100 100 0

Sample Output 2

73074801

Sample Input 3

60522 114575 7559

Sample Output 3

479519525


N,M,K = map(int,input().split())
mod = 998244353
ans = (M**N)%mod
def combination(n,k):
    bunbo,bunsi = 1,1
    for i in range(k):
        bunsi = bunsi*(n-i)%mod
        bunbo = bunbo*(i+1)%mod
    return bunsi*pow(bunbo,mod-2,mod)%mod

for t in range(K+1,N):
    tmp = combination(N-1,t)
    ans = (ans - (tmp*M%mod)*pow(M-1,N-1-t,mod)%mod)%mod
print(ans)


# 入力
S = input()

# 処理&出力
if S == 'ABC':
    print('ARC')
elif S == 'ARC':
    print('ABC')
else:
    print('IDK')

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


s=input()
if s == "ABC":
    print("ARC")
else:
    print("ABC")


import math
import numpy as np
import sys
import os
from operator import mul

sys.setrecursionlimit(10**7)

def _S(): return sys.stdin.readline().rstrip()
def I(): return int(_S())
def LS(): return list(_S().split())
def LI(): return list(map(int,LS()))

if os.getenv("LOCAL"):
    inputFile = basename_without_ext = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
    sys.stdin = open(inputFile, "r")
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

N,K = LI()
s = set()
for i in range(K):
    _ = I()
    s.update(LI())

print(N-len(s))

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n,k = LI()
    d = [0]*n
    for _ in range(k):
        LI()
        a = LI()
        for i in a:
            d[i-1] = 1
    print(n-sum(d))
    return

#Solve
if __name__ == "__main__":
    solve()


n, k = [int(x) for x in input().split()]
using = { x:0 for x in range(1, n + 1)}
for _ in range(k):
    nbs = int(input())
    users = [int(x) for x in input().split()]
    for use in users:
        using[use] += 1
    victims = 0
#print(using)
for i, v in using.items():
    #print(v)
    if v == 0:
        victims += 1
print(victims)


n,k = map(int,input().split())
s = set()
for i in range(k):
    d = input()
    a = input().split()
    s |= set(a)
print(n-len(s))


import collections

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

gb = [1]*n;
for i in range(m):
    a,b = map(int, input().split())
    a -= 1
    b -= 1
    if h[a]<h[b]:
        gb[a] = 0
    else:
        gb[b] = 0

l = collections.Counter(gb)
print(l[1])

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


x = int(input())

for a in range(1000):
    for b range(1000):
        if a ** 5 - b ** 5 == x:
            print(a,b)
            exit()

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


def abc166_d():
  x = int(input())

  def divisor(n):
    # nの約数列挙、戻り値はsortされていない
    ret = []
    for i in range(1, int(n**0.5)+1):
      if n % i == 0:
        ret.append(i)
        ret.append(n//i)
    return ret

  divs = sorted(divisor(x))
  a = 0
  b = divs[1]
  while True:
    if a**5 - (a-b)**5 == x:
      print(a, b)
      return
    a += 1

abc166_d()


x = int(input())
for a in range(-100,100):
    f = 0
    for b in range(-100,100):
        if a**5-b**5==x:
            print(a,b)
            f = 1
            break
    if f:
        break


n = int(input())
a = [int(x) for x in input().split()]
c = 0
for i in range(n):
    for j in range(i - 1):
        if i - j == a[i] + a[j]:
            c += 1
print(c)

Score: 500 points

Problem Statement

You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.

There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.

According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.

The absolute difference of their attendee numbers is equal to the sum of their heights.

There are \frac{N(N-1)}{2} ways to choose two from the N attendees and make a pair. Among them, how many satisfy the condition above?

P.S.: We cannot let you know the secret.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the number of pairs satisfying the condition.

Sample Input 1

6
2 3 3 1 3 1

Sample Output 1

3

A_1 + A_4 = 3, so the pair of Attendee 1 and 4 satisfy the condition.

A_2 + A_6 = 4, so the pair of Attendee 2 and 6 satisfy the condition.

A_4 + A_6 = 2, so the pair of Attendee 4 and 6 satisfy the condition.

No other pair satisfies the condition, so you should print 3.

Sample Input 2

6
5 2 4 2 8 8

Sample Output 2

0

No pair satisfies the condition, so you should print 0.

Sample Input 3

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

Sample Output 3

22


# Problem E - This Message Will Self-Destruct in 5s

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

# initialization
tmp_1 = {}
ans = 0

# count
for i in range(1, N+1):
    if i+a_nums[i-1] in tmp_1:
        tmp_1[i + a_nums[i-1]] += 1
    else:
        tmp_1[i + a_nums[i-1]] = 1

# count 2
for j in range(1, N+1):
    if j-a_nums[j-1] in tmp_1:
        ans += tmp_1[j-a_nums[j-1]]

# output
print(ans)


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

for i in range(a, b + 1):
    if i % k == 0:
        print('OK')
        sys.exit(0)
print('NG')

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


K=int(input())
A=list(map(int,input().split()))
D=A[0]//K
E=A[1]//K
if (E-D)>0:
  print("OK")
elif (A[0]==A[1] and A[0]%K==0):
  print("OK")
else:
  print("NG")


import sys
K = int(input())
A, B = map(int, input().split(" "))
for i in range(A, B+1):
  if i % K == 0:
    print("OK")
    sys.exit()
print("NG")


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

if b-a+1 >= K or b%K == 0 or a%K == 0:
    print('OK')
else:
    print('NG')


X = int(input())
money = 100
count = 0
while money < X:
    count += 1
    money = int(money * 1.01)
print(count)

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


X = int(input())
C = 100
year = 0
while C < X:
    plus = int(C / 100)
    C += plus
    year += 1
print(year)


def f(n, m, arrs=[], arr=[]):
    if len(arr) == n:
        arrs.append(arr)
    else:
        if len(arr) == 0:
            for i in range(1, m + 1):
                f(n, m, arrs, arr + [i])
        else:
            for i in range(arr[-1], m + 1):
                f(n, m, arrs, arr + [i])
    return arrs

n, m, q = map(int, input().split())
Q = []
for _ in range(q):
    a, b, c, d = map(int, input().split())
    Q.append((a, b, c, d))
#print(memo)
ans = 0
for ball in f(n, m):
    a = 0
    #print(ball)
    for q in Q:
        if ball[q[1] - 1] - ball[q[0] - 1] == q[2]:
            a += q[3]
    ans = max(ans, a)
print(ans)

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

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

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


import itertools
N, M, Q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(Q)]
M_chr = []
for i in range(1,M+1):
    M_chr.append(str(i))
As = list(itertools.combinations(M_chr, N))
pointA_max = 0
for i, A in enumerate(As):
    pointA = 0
    for i in range(Q):
        a = abcd[i][0]
        b = abcd[i][1]
        c = abcd[i][2]
        d = abcd[i][3]
        if int(A[b-1])-int(A[a-1]) == c:
            pointA = pointA + d
    if pointA_max < pointA:
        pointA_max = pointA
print(pointA_max)


import itertools
n,m,q = map(int,input().split())
num = [i for i in range(1,m+1)]
l = []
for i in range(q):
    r = list(map(int,input().split()))
    l.append(r)
l.sort()
stock = list(itertools.combinations_with_replacement(num, n))
ans = 0
for i in stock:
    s = 0
    for j in l:
        if i[j[1]-1] - i[j[0]-1] == j[2]:
            s += j[3]
            #print(s)
        #print(i[j[1]-1] - i[j[0]-1])
    if ans < s:
        ans = s
print(ans)


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

c=[]

for x in range(n+1):

    c.append(int(a*x/b)-int(x/b))

print(max(c))

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


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

n = N // 2

for i in range(M):
    A = n - i
    B = n + i + 1
    print(A,B)

Score : 500 points

Problem Statement

You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)
N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:

For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.

Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.

You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

Constraints

1 \leq M

M \times 2 +1 \leq N \leq 200000

Input

Input is given from Standard Input in the following format:

N M

Output

Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.

The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.

The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.

The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.

The 4-th round is fought by C and D, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 1, 2, 3, and 4, respectively.

No player fights the same opponent more than once during the four rounds, so this solution will be accepted.

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


a,b=map(int,input().split())
for i in range(1,b+1):
    print(i,a-i)


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

if s[0] > s[1]:
	print("safe")
else:
    print("unsafe")

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


S, W = map(int, input().split())
print('unsafe' if S <= W else 'safe')


N = int(input())
A = []
for _ in range(N):
  A.append(input())
B = list(set(A))
print(len(B))

Score : 300 points

Problem Statement

You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.

How many kinds of items did you get?

Constraints

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

S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


n=int(input())
s={input() for i in range(n)}
print(len(s))


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

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

count=0

for i in A :
    count += i
    if count > n :
        #print("-1")
        break
    else :
        pass

if n>= count:
    print(n-count)
else:
    print("-1")

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


N,M = map(int,input().split(" "))
somme=0
suite = input().split(" ")
for i in range(M):
  somme+=int(suite[i])
if somme>N:
  print(-1)
else:
  print(N-somme)


n=int(input())

f=[0 for i in range(n)]
for i in input().split():
  f[int(i)-1]+=1
print(*f)

Score : 300 points

Problem Statement

A company has N members, who are assigned ID numbers 1, ..., N.

Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number.

When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X.

You are given the information that the immediate boss of the member numbered i is the member numbered A_i. For each member, find how many immediate subordinates it has.

Constraints

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

1 \leq A_i < i

Input

Input is given from Standard Input in the following format:

N
A_2 ... A_N

Output

For each of the members numbered 1, 2, ..., N, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered 1 has two immediate subordinates: the members numbered 2 and 3.

The member numbered 2 has two immediate subordinates: the members numbered 4 and 5.

The members numbered 3, 4, and 5 do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0


N = int(input())
array = list(map(int, input().strip().split()))
array.sort()
ansarray = []
ansnum = 1
ans = 0
ansindex = 0
for i in range (1,N):
    for j in range(ansindex,N-1):
        if (array[j] == i):
            ans += 1
            ansindex += 1
        else:
            ansarray.append(ans)
            ans = 0
            break
        if(j == N-2):
            ansarray.append(ans)
            ansindex += 1
for i in range(N-len(ansarray)):
    ansarray.append("0")
for i in range(N):
    print(ansarray[i])


N,K = map(int,input().split())
Mod = 10**9+7

ans = 0

for i in range(K,N+2):
  Min = i*(i-1)/2
  Max = i*(2*N-i+1)/2
  ans += Max-Min+1
print(ans%Mod)


k = 0
n = int(input())
for i in range(n+1):
  if i % 3 != 0 and i % 5 != 0:
    k += i

print(k)

Score : 200 points

Problem Statement

Let us define the FizzBuzz sequence a_1,a_2,... as follows:

If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}.

If the above does not hold but 3 divides i, a_i=\mbox{Fizz}.

If none of the above holds but 5 divides i, a_i=\mbox{Buzz}.

If none of the above holds, a_i=i.

Find the sum of all numbers among the first N terms of the FizzBuzz sequence.

Constraints

1 \leq N \leq 10^6

Input

Input is given from Standard Input in the following format:

N

Output

Print the sum of all numbers among the first N terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first 15 terms of the FizzBuzz sequence are:

1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}

Among them, numbers are 1,2,4,7,8,11,13,14, and the sum of them is 60.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.


Score : 600 points

Problem Statement

Given is an integer sequence A_1, ..., A_N of length N.

We will choose exactly \left\lfloor \frac{N}{2} \right\rfloor elements from this sequence so that no two adjacent elements are chosen.

Find the maximum possible sum of the chosen elements.

Here \lfloor x \rfloor denotes the greatest integer not greater than x.

Constraints

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

|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 ... A_N

Output

Print the maximum possible sum of the chosen elements.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

12

Choosing 2, 4, and 6 makes the sum 12, which is the maximum possible value.

Sample Input 2

5
-1000 -100 -10 0 10

Sample Output 2

0

Choosing -10 and 10 makes the sum 0, which is the maximum possible value.

Sample Input 3

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

Watch out for overflow.

Sample Input 4

27
18 -28 18 28 -45 90 -45 23 -53 60 28 -74 -71 35 -26 -62 49 -77 57 24 -70 -93 69 -99 59 57 -49

Sample Output 4

295


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

q = n // k
mod = n % k
ans_mod = k-mod

if mod<ans_mod:
  print(mod)
else:
  print(ans_mod)

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


k = int(input())

def runrun(n):
  if n == 1:
    return([int(x) for x in range(1, 10)])
  key = runrun(n-1)
  key_2 = []
  for value in key:
    p = value%10
    for t in range(-1, 2):
      if 0 <= p+t <= 9:
        key_2.append(value*10+p+t)
  return key_2

runrun_list = []
for i in range(1, 11):
  runrun_list = runrun_list+runrun(i)
  runrun_list.sort()
print(runrun_list[k-1])

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the 32-bit signed integer type.


N,K,C = map(int,(input().split()))
S = list(input())
ol = []
ans = []
for i in range(N):
    if S[i] == "o":
        ol.append(i)

for i in ol:
    if i != ol[0]:
        now = ol[0]
    else:
        if len(ol)>1:
            now = ol[1]
    c = 1
    for j in ol:
        if j > now+C:
            if j != i:
                now = j
                c += 1
        if c >= K:
            break
    if c < K:
        ans.append(i)
for i in ans:
    print(i+1)

Score : 500 points

Problem Statement

Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.

You are given an integer C and a string S. Takahashi will choose his workdays as follows:

After working for a day, he will refrain from working on the subsequent C days.

If the i-th character of S is x, he will not work on Day i, where Day 1 is tomorrow, Day 2 is the day after tomorrow, and so on.

Find all days on which Takahashi is bound to work.

Constraints

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

1 \leq K \leq N

0 \leq C \leq N

The length of S is N.

Each character of S is o or x.

Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

Input

Input is given from Standard Input in the following format:

N K C
S

Output

Print all days on which Takahashi is bound to work in ascending order, one per line.

Sample Input 1

11 3 2
ooxxxoxxxoo

Sample Output 1

6

Takahashi is going to work on 3 days out of the 11 days. After working for a day, he will refrain from working on the subsequent 2 days.

There are four possible choices for his workdays: Day 1,6,10, Day 1,6,11, Day 2,6,10, and Day 2,6,11.

Thus, he is bound to work on Day 6.

Sample Input 2

5 2 3
ooxoo

Sample Output 2

1
5

There is only one possible choice for his workdays: Day 1,5.

Sample Input 3

5 1 0
ooooo

Sample Output 3

There may be no days on which he is bound to work.

Sample Input 4

16 4 3
ooxxoxoxxxoxoxxo

Sample Output 4

11
16


import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    max_i = int(math.log2(N))
    div = []
    for i in range(1,int(math.sqrt(N))+1):
        if N % i == 0:
            div.append((i,N//i)); div.append((N//i,i))

    ans = 0
    for a,b in div:
        if a == 1:
            for i in range(1,int(math.sqrt(b-1))+1):
                if (b-1) % i == 0:
                    p = 2 - (i*i == b-1) - (i == 1)
                    ans += p
        else:
            for i in range(1,max_i+1):
                c = round(math.pow(a,1/i))
                if c ** i == a:
                    if b % c == 1: ans += 1
    print(ans)

if __name__ == '__main__':
    main()

Score : 600 points

Problem Statement

Given is a positive integer N.

We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.

Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.

In how many choices of K will N become 1 in the end?

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of choices of K in which N becomes 1 in the end.

Sample Input 1

6

Sample Output 1

3

There are three choices of K in which N becomes 1 in the end: 2, 5, and 6.

In each of these choices, N will change as follows:

When K=2: 6 \to 3 \to 1

When K=5: 6 \to 1

When K=6: 6 \to 1

Sample Input 2

3141

Sample Output 2

13

Sample Input 3

314159265358

Sample Output 3

9


n=int(input())
ans=1
s=set()
for i in range(1,int(n**0.5)+1):
  if n%(i+1)==0:
    k=n
    cnt=1
    c=0
    while k%(i+1)==0:
      k//=(i+1)
      cnt*=(i+1)
      if cnt not in s:
        s.add(cnt)
        c+=1
    for j in range(1,c+1):
      if k%((i+1)**j)==1:
        ans+=1
d=dict()
k=n-1
for i in range(1,int((n-1)**0.5)+1):
  t=0
  while k%(i+1)==0:
    k//=(i+1)
    t+=1
  if t>0:
    if i+1 not in d:
      d[i+1]=t
    else:
      d[i+1]+=t
if k>1:
  if k not in d:
    d[k]=1
  else:
    d[k]+=1
d=list(d.items())
m=1
for p,root in d:
  m*=(root+1)
print(ans+m-1)


s = str(input())
if S[2]==S[3] and S[4]==S[5]:
    print("Yes")
else:
    print("No")

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

S is a string of length 6 consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


S=input()                                               # 1行1列

if S[2]==S[3] and S[4]==S[5]:
	print('Yes')
else:
	print('No')


Score : 200 points

Problem Statement

Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)

Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

Constraints

0 \leq X \leq 10^9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.


N,X,Y = map(int, input().split())
l = [0]*N
X -= 1
Y -= 1
for i in range(N-1):
  for j in range(i+1,N):
    k = min(abs(j-i),abs(X-i)+abs(Y-j)+1,abs(X-j)+abs(Y-i)+1)
    l[k] += 1
for i in range(1,N):
  print(l[i])

Score : 400 points

Problem Statement

We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:

For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.

There is an edge between Vertex X and Vertex Y.

For each k=1,2,...,N-1, solve the problem below:

Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

Constraints

3 \leq N \leq 2 \times 10^3

1 \leq X,Y \leq N

X+1 < Y

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X Y

Output

For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

Sample Input 1

5 2 4

Sample Output 1

5
4
1
0

The graph in this input is as follows:

There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).

There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).

There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).

There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.

Sample Input 2

3 1 3

Sample Output 2

3
0

The graph in this input is as follows:

Sample Input 3

7 3 7

Sample Output 3

7
8
4
2
0
0

Sample Input 4

10 4 8

Sample Output 4

10
12
10
8
4
1
0
0
0


from collections import deque

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

ret = [0] * N

vec = [[] for _ in range(N)]
for i in range(N - 1) :
  vec[i].append(i + 1)
  vec[i + 1].append(i)
vec[X - 1].append(Y - 1)
vec[Y - 1].append(X - 1)

for i in range(N) :
  dist = [-1] * N
  dist[i] = 0
  q = deque([i])
  while q :
    cur = q.popleft()
    cd = dist[cur]
    for nex in vec[cur] :
      if dist[nex] != -1 : continue
      q.append(nex)
      dist[nex] = cd + 1

  for i in range(N) :
    ret[dist[i]] += 1

for i in range(1, N) :
  print(ret[i] // 2)


Score : 100 points

Problem Statement

We have N+M balls, each of which has an integer written on it.

It is known that:

The numbers written on N of the balls are even.

The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

Constraints

0 \leq N,M \leq 100

2 \leq N+M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

2 1

Sample Output 1

1

For example, let us assume that the numbers written on the three balls are 1,2,4.

If we choose the two balls with 1 and 2, the sum is odd;

If we choose the two balls with 1 and 4, the sum is odd;

If we choose the two balls with 2 and 4, the sum is even.

Thus, the answer is 1.

Sample Input 2

4 3

Sample Output 2

9

Sample Input 3

1 1

Sample Output 3

0

Sample Input 4

13 3

Sample Output 4

81

Sample Input 5

0 3

Sample Output 5

3


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

ans = 0

ans += n*(n-1)/2
ans += m*(m-1)/2

print(int(ans))


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

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

if N !=0 and N != 1:
    a = combinations_count(N, 2)
else:
    a = 0

if M !=0 and M != 0:
    b = combinations_count(M, 2)
else:
    b = 0

print(a+b)


def kaibun(s):
    #print('[debug]',s)

    for i in range(len(s) // 2):
        if s[i] != s[len(s)-1 - i]:
            return False

    return True

def main():
    S = input()
    N = len(S)
    if kaibun(S) == False:
        #print('[debug]','if 1')
        print('No')
        return

    if kaibun(S[0:(N-1)//2]) == False:
        #print('[debug]','if 2')
        print('No')
        return
    if kaibun(S[(N+3)//2 - 1:N]) == False:
        #print('[debug]','if 3')
        print('No')
        return

    print('Yes')

if __name__ == '__main__':
    main()

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No


# import bisect
# from collections import Counter, deque
# import copy
# from fractions import gcd
# from functools import reduce
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np
import sys
sys.setrecursionlimit(10 ** 5 + 10)
# input = sys.stdin.readline

def resolve():

    S=str(input())
    l=len(S)
    """
    print(S[(l + 3) // 2-1:])
    print(S[l-1:(l + 3) // 2-2:-1])
    """

    if S[:(l-1)//2+1-1]==S[(l-1)//2-1::-1] and S[(l + 3) // 2-1 :]==S[l-1:(l + 3) // 2-2:-1] and \
        S==S[::-1]:
        print('Yes')
    else:
        print('No')

resolve()


Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


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

#aに含まれる要素とその個数を取得する
d = {}
for i in range(n):
	d[a[i]] = d.get(a[i], 0) + 1

# print(d)

for i in range(n):
	tmp = a[i]
	print(d[tmp] - 1)

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


import itertools

if __name__ == "__main__":
    N = int(input())
    A = input().split()
    all = len(tuple(filter(lambda t: t[0] == t[1], itertools.combinations(A, 2))))
    for x in range(N):
        count = A.count(A[x])
        tmp = tuple(["0" for _ in range(count)])
        result = tuple(filter(lambda t: t[0] == t[1], itertools.combinations(tmp, 2)))
        print(all-len(result))


ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))

import numpy as np

n = ii()
a = li()

def cmb(n, r):
    if n - r < r: r = n - r
    if n == 0: return 0
    if n == 1: 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

memo_cnt = [0]*(n+1)
memo_cmb = [0]*(n+1)
memo_cmb2 = [0]*(n+1)

for i in range(n):
    memo_cnt[a[i]] += 1

for i in range(n):

    if memo_cnt[i] >= 3:
        memo_cmb[i] = cmb(memo_cnt[i],2)
        memo_cmb2[i] = cmb(memo_cnt[i]-1,2)
    elif memo_cnt[i] == 2:
        memo_cmb[i] = cmb(memo_cnt[i],2)

cmb_cumsum = np.array(memo_cmb).cumsum()

# print('cumsum')
# print(memo_cnt)
# print(memo_cmb)
# print(cmb_cumsum)

for i in range(n):
    a_now = a[i]
    itself = memo_cmb2[a_now]

    other = cmb_cumsum[a_now-1] + cmb_cumsum[-1] - cmb_cumsum[a_now]

    print(itself + other)


h, w, k = map(int, input().split())
s = [list(map(int, list(input()))) for _ in range(h)]
result = []
if h*w<=k:
    result.append(0)
else:
    for i in range(2**(h-1)):
        checker, num, p = 0, i ,[0]
        for _ in range(h):
            p.append(p[-1]+num%2)
            checker += num%2
            num >>= 1
        x = 0
        c = [0 for _ in range(checker+1)]
        for j in range(w):
            num = i
            nex = [0 for _ in range(checker+1)]
            for m in range(h):
                nex[p[m]] += s[m][j]
            if max(nex) > k:
                x = float('inf')
                break

            if all(nex[m]+c[m] <= k for m in range(checker+1)):
                c = [c[I]+nex[I] for I in range(checker+1)]
            else:
                x += 1
                c = nex
        result.append(checker+x)
print(min(result))

Score : 500 points

Problem Statement

We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.

The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.

We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.

How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

Constraints

1 \leq H \leq 10

1 \leq W \leq 1000

1 \leq K \leq H \times W

S_{i,j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

Sample Input 1

3 5 4
11100
10001
00111

Sample Output 1

2

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.

Note that we cannot cut the bar in the ways shown in the two figures to the right.

Sample Input 2

3 5 8
11100
10001
00111

Sample Output 2

0

No cut is needed.

Sample Input 3

4 10 4
1110010010
1000101110
0011101001
1101000111

Sample Output 3

3


Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.


Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


h, w = map(int, input().split(' '))
print(int(h * w / 2) + h * w % 2)


s = input()
n = len(s)
if n % 2 != 0:
  print('No')
  exit()
q = n // 2
ss = 'hi' * q
if s == ss:
  print('Yes')
else:
  print('No')

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

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

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


S = input()

if 'hi' in S:
    print('Yes')
else:
    print('No')


S = input
if S[0] == S[1] and S[1] == S[2]:
  print('No')
else:
  print('Yes')

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


s = input()

a = 0

for i in range(3):
    if s[i] == "A":
        a += 1

if a == 0 or a == 3:
    print("No")
else:
    print("Yes")


def main():
    s = input()
    if s.__contains__("A") and s.__contains__("B"):
        print("Yes")
    else:
        print("No")

if __name__ == '__main__':
    main()


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

period = a + b
num_periods = n // period

remainder = n - (a+b)*num_periods

answer = a*num_periods + min(remainder, a)
print(answer)

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


import sys
input = sys.stdin.readline

def main():
    N, A, B = map(int, input().split())
    syo = N // (A + B)
    amari = N % (A + B)
    print(syo * A + min(amari, A))

if __name__ == "__main__":
    main()


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

mod = N%C
quo = N//C

if A == 0:
    print(0)
elif B == 0:
    print(N)
elif quo == 0:
    if N >= A:
        print(N)
    else:
        print(N-(N%A))
elif mod == 0:
    print(quo*A)
elif mod <= A:
    print((quo)*A+mod)
else:
    print((quo)*A+(mod - mod%A))


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

s = "b"*a + "r"*b
s = s*(10**8)
print(s[:n].count("b"))


N,A,B = [int(s) for s in input().split()]

x1 = N // (A+B) * A
mod = N % (A+B)

print(x1 + mod) if mod < A else print(x1 + A)


# coding:utf-8

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

if A == 0:
    print(0)
else:
    if N <= A:
        print(N)
    else:
        ans, rem = divmod(N, A+B)
        ans *= A
        if rem >= A:
            ans += A
        else:
            ans += rem
        print(ans)


# coding: utf-8
# Your code here!
import numpy as np
import sys
A,B=map(int,input().split())

X=int(A/0.08)+1
Y=int(B/0.10)
answer=10**5

for i in range(Y,X):
    if int(i*0.08)==A and int(i*0.1)==B and answer>i:
        answer=i

if answer!=10**5:
    print(answer)
else:
    print(-1)

Score : 300 points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is 8 percent and 10 percent, the amount of consumption tax levied on it is A yen and B yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

1 \leq A \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is 25 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2 yen.

When the consumption tax rate is 10 percent: \lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2 yen.

Thus, the price of 25 yen satisfies the condition. There are other possible prices, such as 26 yen, but print the minimum such price, 25.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is 100 yen, the amount of consumption tax levied on it is:

When the consumption tax rate is 8 percent: \lfloor 100 \times 0.08 \rfloor = 8 yen.

When the consumption tax rate is 10 percent: \lfloor 100 \times 0.1 \rfloor = 10 yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.


import math
A, B = map(float, input().split())
lowerA = math.ceil(A/0.08)
upperA = math.floor((A+1)/0.08)
lowerB = math.ceil(B/0.1)
upperB = math.floor((B+1)/0.1)
answer = -1
for i in range(lowerA, upperA):
  if (lowerB <= i) and (i <= upperB):
    answer = i
    break
print(answer)


A,B = map(int,input().split())
X = B * 10
for i in range(X,X+10):
  if int(i * 0.08) == A:
    print(i)
    exit()
print('-1')


P8, P10 = map(int, input().split())

import math

price1_min = math.floor(P8/0.08)

price1_max = math.floor((P8+1)/0.08)-1

price2_min = math.floor(P10/0.10)

price2_max = math.floor((P10+1)/0.10)-1

if (price1_max >= price2_min) and (price2_max >= price1_min):
    print(max(price2_min, price1_min))
else:
    print(-1)


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

n=1
while n<=2*10**4:
  if int(n*0.08)==a and int(n*0.1)==b:
    print(n)
    exit()
  else:
    n+=1
print(-1)


A, B = map(int, input().split())
aaa = []
for i in range(1, 101):
  if int(i*0.08) == A and int(i*0.1) == B:
    aaa.append(i)
if len(aaa) >= 1:
  print(min(aaa))
else:
  print(-1)


from collections import deque
S = deque(list(input().strip()))
Q = int(input())
P = 0
for _ in range(Q):
    q = list(input().split())
    if q[0]=="1":
        P += 1
        P = P%2
    else:
        c = q[2]
        if q[1]=="1":
            if P==0:
                S.appendleft(c)
            else:
                S.append(c)
        else:
            if P==0:
                S.append(c)
            else:
                S.appendleft(c)
if P==1:
    S = S[::-1]
print("".join(S))

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


s=input()
q=int(input())
cnt=0
for i in range(q):
    j=tuple(input().split())
    if  int(j[0])!=1 :
        if (cnt+int(j[1]))%2==1:
            s=j[2]+s
        else:
            s=s+j[2]
    else:
        cnt+=1
if cnt%2==0:
    print(s)
else:
    print(s[::-1])


a = int(input())
if a % 2 == 0:
    print(a//2)
else:
    print(a//2 + 1)

Score : 100 points

Problem Statement

Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

N is an integer.

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the 1-st, 2-nd pages on the 1-st sheet, 3-rd and 4-th pages on the 2-nd sheet, and 5-th page on the 3-rd sheet, we can print all the data on 3 sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50


import math
A = int(input())
print(math.ceil(A/2))


Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


import sys
sys.setrecursionlimit(10**5)

def DFS(i):
    if i not in done:
        done.add(i)
        circle.add(i)
        for f in F[i]:
            DFS(f)
    else:
        return

N,M,K=map(int,input().split())
F=[[] for _ in range(N)]
B=[[] for _ in range(N)]

for f in range(M):
    f1,f2=map(int,input().split())
    F[f1-1].append(f2-1)
    F[f2-1].append(f1-1)
for b in range(K):
    b1,b2=map(int,input().split())
    B[b1-1].append(b2-1)
    B[b2-1].append(b1-1)

Group=[]
circle=set()
done=set()
for i in range(N):
    if i not in done:
        DFS(i)
        Group.append(circle)
        circle=set()

ans=[-1 for _ in range(N)]
for i in range(N):
    for j in range(len(Group)):
        if i in Group[j]:
            ans[i]+=len(Group[j])
            break
    for fr in F[i]:
        if fr in Group[j]:
            ans[i]-=1
    for bl in B[i]:
        if bl in Group[j]:
            ans[i]-=1

print(*ans)

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

(A_i, B_i) \neq (A_j, B_j) (i \neq j)

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

5 10 0
1 2
1 3
1 4
1 5
3 2
2 4
2 5
4 3
5 3
4 5

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby, product
    from bisect import bisect_left,bisect_right
    from heapq import heapify, heappop, heappush
    import math
    #from math import gcd

    #inf = 10**17
    #mod = 10**9 + 7

    def segfunc(x, y):
        return x | y

    def init(arr):
        for i in range(n):
            seg[i+num-1] = {arr[i]}
        for i in range(num-2,-1,-1) :
            seg[i] = segfunc(seg[2*i+1],seg[2*i+2])

    def update(k,x):
        k += num-1
        seg[k].clear()
        seg[k] = {x}
        while k:
            k = (k-1)//2
            seg[k].clear()
            seg[k] = segfunc(seg[k*2+1],seg[k*2+2])

    def query(p,q):
        if q<=p:
            return ide_ele
        p += num-1
        q += num-2
        res=ide_ele
        while q-p>1:
            if p&1 == 0:
                res = segfunc(res,seg[p])
            if q&1 == 1:
                res = segfunc(res,seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = segfunc(res,seg[p])
        else:
            res = segfunc(segfunc(res,seg[p]),seg[q])
        return res

    n = int(input())
    s = list(input().rstrip())
    for i in range(n):
        s[i] = ord(s[i]) - 97

    ide_ele = set()

    num =2**((n-1).bit_length())

    # セグ木初期化
    seg=[ide_ele]*2*num
    init(s)

    q = int(input())
    for _ in range(q):
        a,b,c = input().rstrip().split()
        if a == '1':
            b = int(b)
            c = ord(c) - 97
            update(b-1, c)
        else:
            b = int(b)
            c = int(c)
            print(len(query(b-1, c)))

if __name__ == '__main__':
    main()

Score : 500 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.

Process Q queries of the following two types:

Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)

Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive).

Constraints

N, Q, i_q, l_q, and r_q are integers.

S is a string consisting of lowercase English letters.

c_q is a lowercase English letter.

1 \leq N \leq 500000

1 \leq Q \leq 20000

|S| = N

1 \leq i_q \leq N

1 \leq l_q \leq r_q \leq N

There is at least one query of type 2 in each testcase.

Input

Input is given from Standard Input in the following format:

N
S
Q
Query_1
\vdots
Query_Q

Here, Query_i in the 4-th through (Q+3)-th lines is one of the following:

1 i_q c_q

2 l_q r_q

Output

For each query of type 2, print a line containing the answer.

Sample Input 1

7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7

Sample Output 1

3
1
5

In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3.

In the second query, S is modified to abcdzbd.

In the third query, a contains one kind of letter: a, so we print 1.

In the fourth query, S is modified to abcazbd.

In the fifth query, S does not change and is still abcazbd.

In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5.


N, R = list(map(int,input().split()))
if N >= 10:
  print(R)
else:
  print(R+100*(10-N))

Score : 100 points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus 100 \times (10 - K) when the member has participated in K contests.

Takahashi has participated in N contests, and his Displayed Rating is R. Find his Inner Rating.

Constraints

All values in input are integers.

1 \leq N \leq 100

0 \leq R \leq 4111

Input

Input is given from Standard Input in the following format:

N R

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in 2 contests, which is less than 10, so his Displayed Rating is his Inner Rating minus 100 \times (10 - 2) = 800.

Thus, Takahashi's Inner Rating is 2919 + 800 = 3719.

Sample Input 2

22 3051

Sample Output 2

3051


n, k = [int(i) for i in input().split()]
cnt = 0
if n == 0:
  print(1)
  exit()
while n != 0:
  n = n // k
  cnt += 1
print(cnt)

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


def resolve_b():
    n, k = map(int, input().split())

    def Base_10_to_n(X, n): # 再帰処理
        if (int(X / n)):
            return Base_10_to_n(int(X / n), n) + str(X % n)
        return str(X % n)

    ans = Base_10_to_n(n, k)
    print(len(str(ans)))
resolve_b()