inf = 10**9
n, m, x = map(int, input().split())
a = [0] * n
c = [0] * n
y = [0] * n
for i in range(n):
    data = list(map(int, input().split()))
    c[i] = data[0]
    a[i] = data[1:]
ans = inf
for i in range(2**n):
    money = 0
    know = [0] * m
    for j in range(n):
        if (i >> j) & 1:
            money += c[j]
            for k in range(m):
                know[k] += a[j][k]
    for z in know:
        if z < x:
            break
    else:
        ans = min(ans, money)

if ans == inf:
    print(-1)
else:
    print(ans)

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


n, m, k = map(int, input().split())
z = 998244353
if n <= k+1:
    a = 1
    for i in range(n):
        a = a*m%z
    print(a)
else:
    a = [m*((m-1)**(n-1))]
    b = [1]
    c = 0
    for i in range(k):
        b.append(int(b[-1]/(i+1)*(n-i-1)%z))
    for i in range(k):
        a.append(int((a[-1]*b[i+1]%z)/b[i]/(m-1)))
    for i in range(k+1):
        c += a[i]
    print(c%z)

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

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

Submitted source-code file size, in bytes.

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

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


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

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


from sys import stdin
from sys import setrecursionlimit
from collections import Counter, deque, defaultdict
from math import floor, ceil
from bisect import bisect_left
setrecursionlimit(100000)

INF = int(1e10)
MOD = int(1e9 + 7)

def input():
    return stdin.readline()[:-1]

def main():
    from builtins import int, map
    S = input()
    if S == 'ABC':
        print("ARC")
    else:
        print("ABC")

if __name__ == '__main__':
    main()


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

Snack = [0] * N

for i in range(K):
    d = int(input())
    A = list(map(int, input().split()))

    for j in range(d):
        Snack[A[j]-1] += 1

sum = 0
for i in range(N):
    if (Snack[i] == 0):
        sum += 1

print(sum)

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


n,k = map(int,input().split())
d = [0 for _ in range(k)]
a = []
for i in range(k):
    d[i] = int(input())
    a.append(list(map(int,input().split())))
sn = [0 for _ in range(n)]
for i in range(k):
    for j in range(d[i]):
        sn[a[i][j]-1] = 1
ans = 0
print(sn.count(0))


n, k = map(int, input().split())
b = [0]*102
for i in  range(k):
    d = int(input())
    a = list(map(int, input().split()))
    for j in a:
        b[j] = 1
print(n - sum(b))


nobs, nroads = [int(x) for x in input().strip().split()]
rec = [False]*nobs
hs = [int(x) for x in input().strip().split()]
d = {}
while nroads > 0:
  src, dst = [int(x) for x in input().strip().split()]
  if src not in d:
    d[src] = [dst]
  else:
    d[src].append(dst)
  nroads -= 1
i = 0
total = 0
for i in range(nobs):
  if not rec[i]:
    q = [i]
    while len(q) > 0:
      src = q.pop(0)
      found = True
      for dst in d[src]:
        if hs[src] <= hs[dst]:
          found = False
          break
        q.append(dst)
      if found:
        total += 1
print(total)

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 b in range(10000):
  for a in range(int(X**(1/5))+1):
    if a**5-b**5 == X:
      ans = str(a)+" "+str(b)
      break
    if a**5+b**5 == X:
      ans = str(a)+" "+str(-b)
      break
print(ans)

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


x=int(input())
for i in range(-120,120):
  for j in range(-120.120):
    if i**5-j**5==x:
      print(i,j)
      break


X = int(input())
for a in range(-200,200):
    for b in range(-200,200):
        if a**5 - b**5 == X:
            print(a,b)
            exit()


# ANSHUL GAUTAM
# IIIT-D

from math import *
from copy import *					# ll = deepcopy(l)
from heapq import *					# heappush(hp,x)
from string import *				# alpha = ascii_lowercase
from random import *				# l.sort(key=lambda l1:l1[0]-l1[1]) => ex: sort on the basis difference
from bisect import *				# bisect_left(arr,x,start,end)  => start and end parameters are temporary
from sys import stdin				# bisect_left return leftmost position where x should be inserted to keep sorted
from sys import maxsize				# minn = -maxsize
from operator import *				# d = sorted(d.items(), key=itemgetter(1))
from itertools import *				# pre = [0] + list(accumulate(l))
from collections import Counter		# d = dict(Counter(l))
from collections import defaultdict # d = defaultdict(list)

'''

'''

def solve(x):
	l = []
	d = {}
	for i in range(-1000,1000):
		zz = i**5
		d[zz] = i
		l.append(zz)
	for a in range(-2000,2000):
		zz = a**5
		if(zz - x in l):
			print(a,d[zz-x])
			return

X = int(stdin.readline())
ans = solve(X)


import math

X = int(input())

def calculate(x):

    loop = True
    b = 0
    while loop:
        tmp1 = x + b ** 5
        a1 = math.pow(tmp1, 1 / 5)

        if float.is_integer(a1):
            print(int(a1), int(b))
            break

        tmp2 = x + (-1 * b) ** 5
        a2 = math.pow(tmp2, 1 / 5)
        if float.is_integer(a2):
            print(int(a2), int(-1*b))
            break
        b = b + 1

calculate(X)


N = int(input())
A = list(map(int,input().split()))
cnt = 0
for i in range(1,N):
    for j in range(N):
        if j+i > N-1:
            break
        else:
            if A[j]+A[j+i] == i:
                cnt += 1
print(cnt)

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


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

as1 = [-(a+i) for i,a in enumerate(As)]
as2 = [a-i for i,a in enumerate(As)]

from collections import defaultdict
d1 = defaultdict(int)
d2 = defaultdict(int)
cnt = 0

for a1,a2 in zip(as1,as2):
    d1[a1] += 1
    d2[a2] += 1
# print(d1,d2)

for k in d1.keys():
    cnt += d1[k]*d2[k]
print(cnt)


n = int(input())
a = list(map(int, input().split()))
plus = {}  # i + A[i]
minus = {}  # i - A[i]
for i in range(n):
    try:
        plus[i + a[i]] += 1
    except:
        plus[i + a[i]] = 1

    if i - a[i] > 0:
        try:
            minus[i - a[i]] += 1
        except:
            minus[i - a[i]] = 1

ans = 0
for key in plus.keys() & minus.keys():
    ans += plus[key] * minus[key]
print(ans)


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
n, *abc = map(int, input().split())
s = [input().rstrip()for _ in range(n)]
cond = {'AB': (0, 1), 'AC': (0, 2), 'BC': (1, 2)}
legend = ('A', 'B', 'C')
ans = []

def dfs(i):
    if -1 in abc:
        return 0
    elif i == n:
        print('Yes')
        print(*ans, sep='\n')
        exit()
        # return 0
    else:
        idx1, idx2 = cond[s[i]]
        abc[idx1] += 1
        abc[idx2] -= 1
        ans.append(legend[idx1])
        dfs(i+1)
        ans.pop()
        abc[idx1] -= 1
        abc[idx2] += 1

        abc[idx1] -= 1
        abc[idx2] += 1
        ans.append(legend[idx2])
        dfs(i+1)
        ans.pop()
        abc[idx1] += 1
        abc[idx2] -= 1

dfs(0)
print('No')

Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

0 \leq A,B,C \leq 10^9

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A


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

if b-a >= k:
    print('OK')
elif a % k < b % k:
    print('NG')
else:
    print('OK')

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


X = int(input())
now_money=100
i = 0
t= 100

while X >= now_money:
    t += t
    i += 1
print(i)

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


A, B, N = map(int, input().split())
X = min(N, B - 1)
print(A * X // B - A * (X // B))

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


from sys import stdin
import sys

A, B, N = [int(x) for x in stdin.readline().rstrip().split()]
# N, M = [int(x) for x in stdin.readline().rstrip().split()]
# U = input().split()
ans = int((A*N)/B)-A*int(N/B)
if N >= B:
    n = int(N/B)
    for i in range(n):
        x = i*B
        temp = ans1 = int((A*(x-1))/B)-A*int((x-1)/B)
        if temp > ans:
            ans = temp
    n = n*B
    ans1 = int((A*(n-1))/B)-A*int((n-1)/B)
    ans3 = int((A*(n+1))/B)-A*int((n+1)/B)
    ans2 = int((A*(B-1))/B)-A*int((B-1)/B)
    ans4 = int((A*(B+1))/B)-A*int((B+1)/B)
    ans5 = int((A*(n))/B)-A*int((n)/B)
else:
    ans1 = ans
    ans2 = ans
    ans3 = ans
    ans4 = ans
    ans5 = ans

print(max(ans, ans1, ans2, ans3, ans4, ans5))


A,B,N = [int(i) for i in input().split()]
x = N
M = A*N//B
ans = -float("inf")

for _ in range(10**6):
    s = A*x//B - A*(x//B)
    ans = max([ans,s])
    x -= 1

print(ans)


a, b, n = map(int, input().split())
x = (int(a*(n-1)/b)-a*int((n-1)/b))
print(x)


import math
a,b,n=map(int,input().split())
ans=0
if b>n:
  ans=math.floor(a*n/b)
else:
  for i in range(b,n+1):
    c=math.floor(a*i/b)-a*math.floor(i/b)
    ans=max(ans,c)
print(ans)


n, m = map(int, input().split())
ans_i = n//2
ans_j = ans_i+1
n_list = [0]*(n+1)
for _ in range(m):
    if n_list[ans_j-2] == 0 and n_list[ans_j-1]:
        ans_j -= 2
    if n_list[ans_i+2] == 0 and n_list[ans_i+1]:
        ans_i += 2

    if abs(ans_j-ans_i) == abs(n-ans_j+ans_i):
        if ans_i <= n-ans_j: ans_j += 1
        else: ans_i -= 1
    print(ans_i, ans_j)

    n_list[ans_i] = 1
    n_list[ans_j] = 1

    ans_i -= 1
    ans_j += 1

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


from bisect import bisect_left
from collections import defaultdict as dd
N = int(input())
As = list(map(int, input().split()))
Es = dd(dict)
for _ in range(N-1):
    f, t = map(int, input().split())
    Es[f-1][t-1] = Es[t-1][f-1] = 1

INF = float('inf')
RET = 0
PROC = 1

stack = []
lismin = [INF] * N
anss = [INF] * N
visited = [False] * N

stack.append((RET, 0, INF))
stack.append((PROC, 0, 0))
while stack:
    cmd, *v = stack.pop()
    if cmd == RET:
        i, backup = v
        lismin[i] = backup
    else:
        node, i = v
        lismin[i] = As[node]
        anss[node] = i+1
        visited[node] = True
        for to in Es[node].keys():
            if not visited[to]:
                x = bisect_left(lismin, As[to])
                stack.append((RET, x, lismin[x]))
                stack.append((PROC, to, x))
for ans in anss:
    print(ans)

Score : 600 points

Problem Statement

We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i.
Vertex i has an integer a_i written on it.
For every integer k from 1 through N, solve the following problem:

We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.

Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.

Constraints

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

1 \leq a_i \leq 10^9

1 \leq u_i , v_i \leq N

u_i \neq v_i

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}

Output

Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.

Sample Input 1

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

Sample Output 1

1
2
3
3
4
4
5
2
2
3

For example, the sequence A obtained from the shortest path from Vertex 1 to Vertex 5 is 1,2,5,3,4. Its longest increasing subsequence is A_1, A_2, A_4, A_5, with the length of 4.


import bisect
import sys
sys.setrecursionlimit(10**9)

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

tree = [[] for i in range(N)]
for i in range(N-1):
  u, v = map(int, input().split())
  tree[u-1].append(v-1); tree[v-1].append(u-1)

ans = [0] * N
ans[0] = 1
INF = 10**10
dp = [INF] * N
dp[0] = A[0]
stack = []
def dfs(node, par, n):
  global ans
  global dp
  global stack
  children = tree[node]
  for child in children:
    if child == par:
      continue
    num = A[child]
    idx = bisect.bisect_left(dp, num)
    stack.append([idx, dp[idx]])
    dp[idx] = num
    ans[child] = max(n, idx+1)
    # ans[child] = bisect.bisect_left(dp, INF)
    dfs(child, node, max(n, idx+1))
    # 巻き戻し
    idx, num = stack.pop()
    dp[idx] = num

dfs(0, -1, 1)
print(*ans, sep='\n')


n = input()
p=input()
p=p[0:-1]
if n==p:
    print("Yes")
else:
    print("No")

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("safe") if s > w else print("unsafe")


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


s, w = map(int, input().split())
if s > w:
  print("safe")
else:
  print("unsafe")


a = int(input())
c= [input() for i in range(a)]
lst = []

for i in range(len(c)):
    if not(c[i] in lst):
        lst.append(c[i])
print(len(lst))

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


 = map(int,input().split())
l = list(map(int,input().split()))
s = 0
for i in range(n):
  s += l[i]
print(max(m-s,-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


date0=input().rstrip().split(" ")
day=int(date0[0])
num=int(date0[1])
date1=input().rstrip().split(" ")
sum=0
for i in range(num):
  sum+=int(date1[i])
if day-sum>=0:
  print(day-sum)
else:
  print(-1)


#!/usr/bin/env python3

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

ans = N-sum(A)

if ans < 0:
    print(-1)
else:
    print(ans)


import bisect,collections,copy,heapq,itertools,math,operator,string
def I(): return int(input())
def S(): return input()
def LI(): return list(map(int,input().split()))
def LS(): return list(input().split())
##################################################
N,M = LI()
A = LI()
for x in A:
    N -= x
print(N if N>=0 else -1)


import sys
import os
import math
import string

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')

def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N = ii()
    A = il()
    ret = [0] * N
    for a in A:
        ret[a - 1] += 1
    print(*ret, sep="\n")

if __name__ == '__main__':
    main()

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())
numbers = list(map(int, input().split()))

result = [0] * N
for i in numbers:
    result[i- 1] += 1

for i in range(N-1):
    print(result[i])
print(0)


N = int(input())

A = map(int, input().split())
AI = sorted(((a, i) for i, a in enumerate(A, 1)), reverse=True)

def solve(a, i, prev):
  pl, pr, ps = i, 0, 0
  for l, r, s in prev:
    yield l, r-1, max(s+abs(r-i)*a, ps+abs(i-pl)*a)
    pl, pr, ps = l, r, s
  yield pl+1, pr, ps+abs(i-pl)*a

prev = [(1, N, 0)]
for a,i in AI:
  prev = [*solve(a,i, prev)]

print(max(s for l, r, s in prev))

Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85


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

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.


n = int(input())
sum = 0
for i in range(1, n):
    if i%3!=0:
        if i%5!=0:
            sum+=i
print(sum)


N = int(input())
l = []
for i in range(N+1):
    if i%3!=0 and i%5!=0:
        l.append(i)
print(sum(l))


import numpy as np
#N=map(int, input().split())
N=int(input())
count=0
for i in range(0,N):
    if i%3!=0 and i%5!=0:
        count=count+i
print(count)


import sys
input = sys.stdin.readline
from itertools import *
from functools import *
from collections import *
from heapq import heapify, heappop, heappush, heappushpop

INF = float('inf')
NIL = - 1

def main():
    N = int(input())

    total = 0
    for n in range(1, N + 1):
        if n % 3 == 0 and n % 5 == 0:
            pass
        elif n % 3 == 0:
            pass
        elif n % 5 == 0:
            pass
        else:
            total += n
    print(total)

if __name__ == '__main__':
    main()


N = int(input())
res = 0
for tmp in range(N):
    i = tmp+1
    if i % 3 == 0 or i % 5 ==0:
        continue
    res += i

print(res)


import sys

# import bisect
# from collections import Counter, deque, defaultdict
# import copy
# from heapq import heappush, heappop, heapify
# import itertools
# from operator import attrgetter, itemgetter
# import math

# from numba import jit
# import numpy as np

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

def main():
    n = int(input())
    a = [0] + list(map(int, readline().split()))

    if n % 2 == 0:
        ans1 = sum(a[::2])
        ans2 = sum(a[1::2])
        print(max(ans1, ans2))
        sys.exit()

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

    # 普通に選ぶ場合
    dp[1][0] = 0
    dp[2][0] = max(a[1], a[2])
    dp[3][0] = max(a[1], a[2], a[3])

    # 1個多く選ぶ場合（奇数個のみ）
    dp[1][1] = a[1]
    dp[3][1] = a[1] + a[3]

    i = 4

    while i < n + 1:
        cur1 = a[i]

        # 偶数だよ
        dp[i][0] = max(dp[i - 1][1], dp[i - 2][0] + cur1)

        i += 1
        cur2 = a[i]

        # 奇数だよ
        dp[i][0] = max(dp[i - 2][0] + cur2, dp[i - 3][0] + cur2, dp[i - 1][0], dp[i - 2][1])
        dp[i][1] = dp[i - 2][1] + cur2

        i += 1

    print(dp[n][0])

if __name__ == '__main__':
    main()

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


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

n = abs(n - k)

if k == n:
    print(0)
    sys.exit()
elif k > n:
    print(min(n, k-n))
    sys.exit()
else:
    while n > k:
        n %= k
    print(min(n%k, abs(n-k)))

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


N, K = map(int, input().split())
rem = N % K
print(min([rem, K - rem]))


k=int(input())
t=[2]+[3]*8+[2]
g=[[1]+[0for i in range(9)]for j in range(100)]
def f(x,y):
    if g[x][y]!=0:
        return g[x][y]
    else:
        p=0
        for i in range(x-1,x+2):
            if 0<=i<10:
                p+=f(i,y-1)
        g[x][y]=p
        return p
c=0
for i in range(10):
    for j in range(1,10):
        if c+f(j,i)>=k:
            p=str(j)
            po=j
            for h in range(i-1,-1,-1):
                for w in range(po-1,po+2):
                    if 0<=w<10:
                        if c+f(w,h)>=k:
                            p+=str(w)
                            po=w
                            break
                        c+=f(w,h)
            print(p)
            exit()
        c+=f(j,i)

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.


url = "https://atcoder.jp/contests/abc161/tasks/abc161_d"

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

    end_r = 3234566667
    count = 0
    start = 0
    flg = False

    if n <= 12:
        print(n)
        exit()
    elif n <= 50000:
        count = n
    elif n > 50000:
        count = 100000 - n
        start = end_r
        flg = True
    while count != 0:
        if flg:
            start -= 1
        else:
            start += 1
        for i in range(len(str(start)) + 1):
            start_li = [int(v) for v in str(start)]
            if i == len(start_li) - 1:
                count -= 1
                break
            elif abs(start_li[i] - start_li[-1]) >= len(start_li):
                break
            elif abs(start_li[i + 1] - start_li[i]) >= 2:
                break

    print(start)

if __name__ == '__main__':
    main()


n,k,c=map(int,input().split())
s=input()
l=list();r=list()
nex=0
for i in range(n):
	if i<nex:
		continue
	if s[i]=="o":
		nex=i+c+1
		l.append(i)
		if len(l)==k:
			break
nex=-1
for i in range(n):
	if i<nex:
		continue
	if s[-i-1]=="o":
		nex=i+c+1
		r.append(n-i-1)
		if len(r)==k:
			break
r=r[::-1]
for i in range(k):
	if l[i]==r[i]:
		print(l[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


# coding: utf-8

def greedy_search(K, C, workable, shift = 1):
    workable = workable[::shift]
    if workable == []:return []
    work_day = 1
    pre_day = workable[0]
    work_list = [workable[0]]
    if work_day == K:
        return work_list
    if workable[1:] == []:
        return []
    for work in workable[1:]:
        if shift*(pre_day + C *shift) >= work*shift:
            continue
        pre_day = work
        work_day += 1
        work_list.append(work)
        if work_day == K:
            return work_list
    return []

def extract(S):
    ret = []
    for idx, s in enumerate(S, 1):
        if s == 'o':
            ret.append(idx)
    return ret

if __name__ == '__main__':
    N, K, C = list(map(int, input().split()))
    S = list(input())
    base = extract(S)
    left = greedy_search(K,C,base,shift=1)
    right= greedy_search(K,C,base,shift=-1)[::-1]
    #print(base)
    #print(left)
    #print(right)
    for i in base:
        left_k = len(left)
        left_margin = left[-1] if left is not [] else -10**10
        for left_idx in range(len(left)):
            if left[left_idx] >= i:
                left_k = left_idx
                left_margin = left[left_idx-1] if left_idx != 0 else -10**10
                break
        right_k = 0
        right_margin = 10 ** 10
        for right_idx in range(len(right)):
            if right[right_idx] > i:
                right_k = len(right) - right_idx
                right_margin = right[right_idx]
                break
        kk = left_k + right_k
        if right_margin - left_margin <= C:
            kk -= 1
        if kk < K:
            print(i)


import math
import random
import sys

sys.setrecursionlimit(10**7)
MAX_INT = 2**62-1
def input() -> str:
    return sys.stdin.readline()

def main():
    n, k, c = map(int, input().split())
    s = input().strip()
    front = set()
    start = 0
    days = k
    while start < n and days:
        if s[start] == 'x':
            start += 1
        else:
            front.add(start)
            days -= 1
            start += c + 1
    # print(front)
    # if len(front) > k:
    #     return

    back = set()
    start = n-1
    days = k
    while start >= 0 and days:
        if s[start] == 'x':
            start -= 1
        else:
            back.add(start)
            days -= 1
            start -= c + 1
    # print(back)
    for i in front & back:
        print(i+1)

if __name__ == "__main__":
    main()


inp = input()
print('Yes' if inp[2] == inp[3] and inp[4] == inp[5] else '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


my=input()
if my[2]==my[3] and my[4]==my[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.


K, N = map(int,input().split())
A = list(map(int, input().split()))
a = A[0]
sub = []
for _ in range(N):
    p = A.pop()
    sub.append(K-p)
    K = p
sub[0] += a
sub.remove(max(sub))
print(sum(sub))

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


from collections import deque

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

g = [[] for _ in range(n)]

for i in range(n - 1):
    g[i].append(i + 1)
    g[i + 1].append(i)
g[x - 1].append(y - 1)
g[y - 1].append(x - 1)

def bfs(g, n_node, start_node):
    dist = [-1] * n_node
    dist[start_node] = 0
    que = deque([start_node])

    while que:
        node = que.popleft()
        for j in g[node]:
            if dist[j] != -1:
                continue
            dist[j] = dist[node] + 1
            que.append(j)
    return dist

ans = [0] * n

for i in range(n):
    dist = bfs(g, n, i)
    for d in dist:
        ans[d] += 1

for a in ans[1:]:
    print(a//2)

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


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

ans = 0
if n >= 2:
    ans += (n*(n-1) / 2)
if m >= 2:
    ans += (m*(m-1) / 2)

print(int(ans))

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


import math

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

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

if N <= 1:
    L = 0
else:
    L = combination_count(N,2)

if M <= 1:
    O = 0
else:
    O = combination_count(M,2)

num = L + O

print(num)


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


s= input()
l = list(s)
ans= "Yes"
if(s != s[::1]):
    ans = "No"
    break
else:
    s1 = s[:len(s)//2]
    s2 = s[len(s)//2+1:]
    if s1!=s2:
        print("No")
    else:
        print("Yes")
print(ans)


s = input()

def is_Palindrome(s):
  mid = len(s) // 2
  if len(s[:mid]) < 1 or len(s[mid+1:]) < 1:
    return False
  if s[:mid] == s[mid+1:]:
    return True
  else:
    return False

mid = len(s) // 2
if is_Palindrome(s) and is_Palindrome(s[:mid]) and is_Palindrome(s[mid+1:]):
  print("Yes")
else:
  print("No")


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


L=int(input())
#D = L//3
#Amari = L%3
#if Amari == 0:
#    print(D**3)
#elif Amari == 1:
#    print(D*D*(D+1))
#else:
#    print(D*(D+1)*(D+1))
print(L**3/27)


n = int(input())
numbers = list(map(int, input().split(' ')))

counters = {}
cevap_list = {}
sayilar = set(numbers)
for i in numbers:
    if i in counters:
        counters[i] += 1
    else:
        counters[i] = 1

sonuc = 0
for sayi in counters:
    count = counters[sayi]
    sonuc += int(count * (count - 1) / 2)

for i in range(n):
    print(sonuc-counters[numbers[i]]+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


def aC(a):
  if a == 0:
    return 0
  return a*(a-1)/2

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

for i in range(0,N):
  pre_A = A[:]
  aaaaa = pre_A[i]
  if aaaaa in d:
    print(d[A[i]])
  else:
    pre_A.pop(i)
    ans = 0
    count = 0
    for i in range(1,N+1):
      aaa = pre_A.count(i)
      ans = ans + aC(aaa)
    print(int(ans))
    d[aaaaa] = int(ans)


import sys

input = sys.stdin.readline
sys.setrecursionlimit(100000)
# mod = 10 ** 9 + 7
mod = 998244353

def read_values():
    return map(int, input().split())

def read_index():
    return map(lambda x: int(x) - 1, input().split())

def read_list():
    return list(read_values())

def read_lists(N):
    return [read_list() for n in range(N)]

class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v

    def __str__(self):
        return str(self.v)

    def ud(self, n):
        if n is None:
            return

        if self.v is None:
            self.v = n
            return
        self.v = self.f(self.v, n)

def main():
    N, S = read_values()
    A = read_list()

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

    for a in A:
        for s in range(S, -1, -1):
            d1 = dp[s][0]
            d2 = (dp[s][1] + (0 if s - a < 0 else dp[s - a][1]) + d1) % mod
            d3 = (dp[s][2] + (0 if s - a < 0 else dp[s - a][1]) + d2) % mod
            dp[s] = (d1, d2, d3)

    print((dp[S][2] - dp[S][1]) % mod)

if __name__ == "__main__":
    main()

Score : 600 points

Problem Statement

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

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this 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(L, R), modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

5

The value of f(L, R) for each pair is as follows, for a total of 5.

f(1,1) = 0

f(1,2) = 1 (for the sequence (1, 2))

f(1,3) = 2 (for (1, 2) and (3))

f(2,2) = 0

f(2,3) = 1 (for (3))

f(3,3) = 1 (for (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

152


#!/usr/bin/env python3
import sys

min_r = 200

def solve(H: int, W: int, s: "List[str]"):
    l = H+W
    global min_r
    def cal_c(cmp, y, x, pre):
        global min_r
        if cmp < min_r :
            if ((y==H-1)&(x==W-1)):
                min_r = cmp+((pre ==".")&(s[y][x]=="#"))*1
            else:
                k = ((pre==".")&(s[y][x]=="#"))*1
                if y < H-1:
                    cal_c(cmp+k, y+1, x, s[y][x])
                if x < W-1:
                    cal_c(cmp+k, y, x+1, s[y][x])

    cal_c(0, 0, 0, ".")
    print(min_r)

    return

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(W)]  # type: "List[str]"
    solve(H, W, s)

if __name__ == '__main__':
    main()

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


from collections import deque
import sys
sys.setrecursionlimit(10 ** 9)
# import numpy as np
# 答えの提出の時にi+1とj+1は忘れないように
h, w = map(int, input().split())
maze = [[-1 for i in range(w)] for j in range(h)]

INF = h*w
countBlack = [[INF for i in range(w)] for j in range(h)]

for i in range(h):
    maze[i] = input()

sx=0
sy=0
queue = deque()
queue.append((sy,sx))
countBlack[sy][sx] = int(maze[0][0]== '#')

while queue:
    y, x = queue.popleft()
    for i,j in [(1,0),(0,1)]:
        ny, nx = y+i, x+j
        if 0 <= nx < w and 0 <= ny < h:
            if countBlack[ny][nx] >= countBlack[y][x]+1:
                if maze[ny][nx] == '#':
                    countBlack[ny][nx] = countBlack[y][x] + 1
                else:
                    countBlack[ny][nx] = countBlack[y][x]
                if ny != h-1 or nx != w-1:
                    queue.append((ny, nx))
                elif countBlack[ny][nx]==0:
                    print(0)
                    exit()

print(countBlack[h-1][w-1])


from math import ceil
H,W=map(int,input().split())

if W%2==0:
    print((W//2)*H)
else:
    print(ceil(W/2)*ceil(H/2)+(W//2)*(H//2))

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())
if h==1 or w == 1:
    print(0)
elif h%2==0:
    print(h*w//2)
else:
    print(h*w//2 +1)


h,w=input().split()
h=int(h)
w=int(w)
ans=h*w//2
if (h*w%2==1):
    ans+=1
print(ans)


N = int(input())
#print(N)
ret = 2 ** (N-1)
print(ret)

Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab


s = {}
s[0] = input()
s[1] = input()
s[2] =input()

def compe(a,b):
    a,b = list(a),list(b)
    L = len(a) if len(a) < len(b) else len(b)
    c = 0
    for i in range(L):
        flg = 0
        for j,(x,y) in enumerate(zip(a[len(a) - i -1:len(a)],b[0:i+1])):
            if x == '?' or y == '?':
                continue
            elif x == y:
                continue
            else:
                flg = 1
                break
        if flg == 0:
            c = i+1
    ab_1 = a + b[c:]
    ab_2 = a[0:len(a)-c] + b
    for i ,(x, y) in enumerate(zip(ab_1,ab_2)):
        if x == '?':
            ab_1[i] = y
    return c,ab_1

junban = [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]]
min_s = 100000
for j in junban:
    p,obj = compe(s[j[0]],s[j[1]])
    q,obj2 = compe(obj,s[j[2]])
    L = len(s[0])+len(s[1])+len(s[2]) - p - q
    if min_s > L:
        min_s = L

print(min_s)

Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.


S = input()
if S == "hi" or S =="hihi" or S =="hihihi" or S =="hihihihi" or S =="hihihihihi":
    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


A, B, M = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
a.sort()
b.sort()
disc = []
for i in range(M):
  disc.append(list(map(int,input().split())))
ans = a[0] + b[0]
for i in range(M):
  if a[disc[i][0]-1] + b[disc[i][1]-1] - disc[i][2] < ans: ans = a[disc[i][0]-1] + b[disc[i][1]-1] - disc[i][2]

print(ans)

Score : 200 points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells A kinds of refrigerators and B kinds of microwaves. The i-th refrigerator ( 1 \le i \le A ) is sold at a_i yen (the currency of Japan), and the j-th microwave ( 1 \le j \le B ) is sold at b_j yen.

You have M discount tickets. With the i-th ticket ( 1 \le i \le M ), you can get a discount of c_i yen from the total price when buying the x_i-th refrigerator and the y_i-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

1 \le A \le 10^5

1 \le B \le 10^5

1 \le M \le 10^5

1 \le a_i , b_i , c_i \le 10^5

1 \le x_i \le A

1 \le y_i \le B

c_i \le a_{x_i} + b_{y_i}

Input

Input is given from Standard Input in the following format:

A B M
a_1 a_2 ... a_A
b_1 b_2 ... b_B
x_1 y_1 c_1
\vdots
x_M y_M c_M

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the 1-st refrigerator and the 2-nd microwave for 3+3-1=5 yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the 1-st refrigerator and the 1-st microwave for 6 yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.


#C
#入力
N=int(input())
X=[list(map(int,input().split())) for i in range(N-1)]

#前提関数
def c_1(X,n,j):#nとの距離がiのノードを返す
    t=X[n-1]
    s=[]
    for i in range(len(t)):
        if t[i]==j:
            s.append(i+1)
    return s

#処理
Y=[ [ -1 for i in range(N)] for j in range(N)]
Z=[ [ 0 for i in range(N)] for j in range(N)]
for i in range(N):
    Y[i][i]=0
for i in X:
    Y[i[0]-1][i[1]-1]=1
    Y[i[1]-1][i[0]-1]=1

for i in range(2):#三段探索する

    for j in range(N):#一列づつ見る
        t=c_1(Y,j+1,i+1)
        for l in t:
            s=c_1(Y,l,1)
            for m in s:
                if Y[j][m-1]==-1:
                    Y[j][m-1]=i+2

Score : 600 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.

Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:

For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.

Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.

Help Takahashi by finding a permutation that satisfies the condition.

Constraints

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

1\leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

If no permutation satisfies the condition, print -1.

Otherwise, print a permutation satisfying the condition, with space in between.
If there are multiple solutions, you can print any of them.

Sample Input 1

5
1 2
1 3
3 4
3 5

Sample Output 1

1 2 5 4 3

The distance between two vertices is 3 for the two pairs (2, 4) and (2, 5).

p_2 + p_4 = 6

p_2\times p_5 = 6

Thus, this permutation satisfies the condition.


s = input()

if s[0]==s[1] and s[1]==s[2] and s[0]==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 = list(input())
if S[0] == S[1] == S[2]:
    print('No')
else:
    print('Yes')


s = input()
if s == 'AAA' or s == 'BBB':
    ans = 'No'
else:
    ans = 'Yes'
print(ans)


s = input()
if s[0] != s[1] or s[1] != s[2]:
    print("Yes")
else:
    print("No")


n,a,b = map(int, input().split())
ans = n //(a+b) * a
if n % (a+b) <= a: ans += n%(a+b)
print(ans)

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.


# coding: utf-8
# Your code here!
N, A, B = map(int, input().split())
i=0
c=A+B
d=0
List=[]
while i<N:
  #print(i)
  if d<A:
    List.append("r")
  else:
    List.append("b")
  if i%c==0:
    d=0
  i+=1
  d+=1
#print(List)
print(List.count("r"))


N, A, B = map(int, input().split())
ans = N//(A+B)*A + min(N%(A+B), A)
print(ans)


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

AA = A*100//8
AF = (A+1)*100//8 + 1 if (A+1)*100%8!=0 else (A+1)*100//8
BB = B*10
AAA = [i for i in range(AA,AF]
BBB = [i for i in range(BB,(B+1)*10)]
AB_list = list(set(AAA)&set(BBB))

ans = min(AB_list) if AB_list and (12<min(AB_list)<=1000) else -1
print(ans)

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 sys
input = sys.stdin.readline
S = input()
Q = int(input())
FQ_dic =tuple()
rev =0
for i in range(Q):
    FQ_dic =tuple(input().split())

    if      FQ_dic[0] =="1": #逆転する
                rev +=1
    else:                   #逆転なし
        if      FQ_dic[1]=="1":     #後ろにつける
            if rev %2 ==0:
                    S = FQ_dic[2] + S
            else:
                    S = S +FQ_dic[2]
        else: #                      #前につける
            if rev %2 ==0:
                    S = S + FQ_dic[2]
            else:
                    S = FQ_dic[2] + S
if rev %2 ==0:
    print(S)
else:
    print(S[::-1])

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_reverse = 0
for i in range(q):
  query = input()

  if query[0] == '1':
    cnt_reverse += 1
  elif (query[2] == '1' and cnt_reverse % 2==0) or (query[2] == '1' and cnt_reverse % 2==1):
    s = query[4] + s
  else:
    s  = s + query[4]
if cnt_reverse%2==1:
  s = s[::-1]
print(s)


import sys
input = sys.stdin.readline

s = input().split()[0]
q = int(input())

left, right = [], []
state = 1
for _ in range(q):
    q_i = input().split()
    if len(q_i) == 1:
        state = (state)%2 + 1
    else:
        _, f, c = q_i
        f = int(f)
        if (f+state)%2 == 0:
            left += [c]
        else:
            right += [c]
if state == 1:
    print(''.join(left[::-1]) + s + ''.join(right))
else:
    print(''.join(right[::-1]) + s + ''.join(left))


from collections import deque

S = input()
Q = int(input())

cur = 1
d = deque([S])

for _ in range(Q):
    ins = input().split()
    if len(ins) == 1:
        cur = 2 if cur == 1 else 1
    else:
        _, f, c = ins
        f = int(f)
        if cur == f == 1 or cur == f == 2:
            d.appendleft(c)
        else:
            d.append(c)

if cur == 1:
    print("".join(d))
else:
    temp = "".join(d)
    print(temp[::-1])


#!/usr/bin/env python3
import sys
from collections import defaultdict

def solve(N: int, P: int, S: str):
    if 10%P == 0:
        sum = 0
        for i in range(1,N+1):
            if int(S[-i]) % P == 0:
                sum += (N-i)+1
        print(sum)
        return
    else:
        sArr = [0] * N
        C = 1
        counts = defaultdict(int)
        for i in range(1,N+1):
            if i == 1:
                sArr[i - 1] = int(S[-1])%P
            else:
                sArr[i-1]  = (int(S[-i])*C + sArr[i-2])%P
            counts[sArr[i-1]]+=1
            C*=10
        sum = 0
        for k in counts:
            c = counts[k]
            sum += int((c*(c-1)/2))
        sum += counts[0]
        print(sum)

    # sum = 0
    # for i in range(N):
    #     sDiv = 0
    #     coeff = 1
    #     for j in range(i,N):
    #         sDiv= (sDiv*coeff + arr[j])%P
    #         coeff*=10
    #         if sDiv == 0:
    #             sum+=1
    # print(sum)
    return

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    S = next(tokens)  # type: int
    solve(N, P, S)

if __name__ == '__main__':
    main()

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


n, p = map(int, input().split())
S = input()

m = [0 for i in range(p)]

ans = 0
m[0] = 1

if p == 2 or p == 5:
    for i in range(n):
        if int(S[i]) % p == 0:
            ans += i+1

else:
    cnt = 10 % p
    for i in range(n):
        s = int(S[n-1-i])
        if i == 0:
            r = s%p
        else:
            r = (cnt*s+r) % p
            cnt = cnt * 10 % p
        if m[r] >= 1:
            ans += m[r]
        m[r] += 1

print(ans)


A=list(map(lambda x: (int(x), False), input().split()))
A+=list(map(lambda x: (int(x), False), input().split()))
A+=list(map(lambda x: (int(x), False), input().split()))

N = int(input())
for _ in range(N):
  n = int(input())
  for a, b in A:
    if a == n:
      b = True
if (A[0][1] and ((A[1][1] and A[2][1]) or \
                       (A[3][1] and A[6][1]) or \
                       (A[4][1] and A[8][1]))) or \
          (A[1][1] and A[4][1] and A[7][1]) or \
          (A[2][1] and A[5][1] and A[8][1]) or \
          (A[3][1] and A[4][1] and A[5][1]) or \
          (A[6][1] and A[7][1] and A[8][1]) or \
          (A[2][1] and A[4][1] and A[6][1]):
    print("YES")
else:
    print("No")

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.


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

count = int(input())

for num in range(count):
    x = int(input())
    for y in range(3):
        if a[y] == x:
            a[y] = 0
    for y in range(3):
        if b[y] == x:
            b[y] = 0
    for y in range(3):
        if c[y] == x:
            c[y] = 0

#ans = 0
#ans = a[0] * a[1] * a[2]
#ans += b[0] * b[1] * b[2]
#ans += c[0] * c[1] * c[2]
#ans += a[0] * b[0] * c[0]
#ans += a[1] * b[1] * c[1]
#ans += a[2] * b[2] * c[2]

#if ans == 0:
#    print("Yes")
if a[0]+a[1]+a[2] == 0:
    print("Yes")
elif b[0]+b[1]+b[2] == 0:
    print("Yes")
elif c[0]+c[1]+c[2] == 0:
    print("Yes")
elif a[0] + b[0] + c[0] ==0:
    print("Yes")
elif a[1] + b[1] + c[1] ==0:
    print("Yes")
elif a[2] + b[2] + c[2] ==0:
    print("Yes")
elif a[0] + b[1] + c[2] == 0:
    print("Yes")
elif a[2] + b[1] + c[0] ==0:
    print("Yes")
else:
    print("No")


A_List_1 = list(map(int,input().split()))
A_List_2 = list(map(int,input().split()))
A_List_3 = list(map(int,input().split()))

N = int(input())
#B_List = []
for i in range(N):
    n = int(input())
    for j in range(3):
        if n == A_List_1[j]:
            A_List_1[j] = 0
        if n == A_List_2[j]:
            A_List_2[j] = 0
        if n == A_List_3[j]:
            A_List_3[j] = 0

sum_1 = A_List_1[0] + A_List_1[1] + A_List_1[2]
sum_2 = A_List_2[0] + A_List_2[1] + A_List_2[2]
sum_3 = A_List_3[0] + A_List_3[1] + A_List_3[2]
naname_1 = A_List_1[0] + A_List_2[1] + A_List_3[2]
naname_2 = A_List_1[2] + A_List_2[1] + A_List_3[0]
tate_0 = A_List_1[0] + A_List_2[0] + A_List_3[0]
tate_1 = A_List_1[1] + A_List_2[1] + A_List_3[1]
tate_2 = A_List_1[2] + A_List_2[2] + A_List_3[2]

if sum_1 == 0 or sum_2 == 0 or sum_3 == 0 or naname_1 == 0 or naname_2 == 0 or tate_0 == 0 or tate_1 == 0 or tate_2 == 0:
    print('Yes')
else:
    print('No')


bingo=[list(map(int,input().split())) for _ in range(3)]
N=int(input())
B=[int(input()) for _ in range(N)]
for i in range(3):
  for b in B:
    if bingo[i][i]==b:
      bingo[i][i]="!"
for j in range(3):
  if bingo[j][0]==bingo[j][1]==bingo[j][2]=="!":
    print("Yes")
    exit()
  if bingo[0][j]==bingo[1][j]==bingo[2][j]=="!":
    print("Yes")
    exit()
  if bingo[0][0]==bingo[1][1]==bingo[2][2]=="!":
    print("Yes")
    exit()
  if bingo[0][2]==bingo[1][1]==bingo[2][0]=="!":
    print("Yes")
    exit()
print("No")


from collections import deque

n,m,k = map(int,input().split())
ans = [[0]*n for i in range(n)]

fre = [[] for i in range(n)]
blo = [[] for i in range(n)]
for i in range(m):
    a,b = map(int,input().split())
    fre[a-1].append(b-1)
    fre[b-1].append(a-1)
for i in range(k):
    a,b = map(int,input().split())
    blo[a-1].append(b-1)
    blo[b-1].append(a-1)

group = [-1]*n
def check():

    count = 1
    for i in range(n):
        if group[i] == -1:
            dfs(i,count)
            count += 1
    return group

def dfs(i,count):
    q = deque([])
    q.append(i)
    while q:
        bef = q.pop()

        for nex in fre[bef]:
            if group[nex] == -1:
                group[nex] = count
                q.append(nex)

check()
for i in range(n):
    if group[i] == -1:
        print(0,end=" ")
    else:
        num = group.count(group[i])
        num -= len(fre[i])
        for j in blo[i]:
            if group[j] == group[i]:
                num -= 1
        print(num-1,end=" ")

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


class UnionFind(object):
    "https://www.kumilog.net/entry/union-find"
    def __init__(self, n=1):
        self.par = [i for i in range(n)]
        self.rank = [0 for _ in range(n)]
        self.size = [1 for _ in range(n)]

    def find(self, x):
        """
        x が属するグループを探索
        """
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):
        """
        x と y のグループを結合
        """
        x = self.find(x)
        y = self.find(y)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
            self.par[y] = x
            self.size[x] += self.size[y]

    def is_same(self, x, y):
        """
        x と y が同じグループか否か
        """
        return self.find(x) == self.find(y)

    def get_size(self, x):
        """
        x が属するグループの要素数
        """
        x = self.find(x)
        return self.size[x]

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

uf = UnionFind(N)
fr = {}
for _ in range(M):
    a, b = map(int, input().split(" "))
    a -= 1
    b -= 1
    uf.union(a, b)
    if fr.get(a) is not None:
        fr[a].append(b)
    else:
        fr[a] = [b]

    if fr.get(b) is not None:
        fr[b].append(a)
    else:
        fr[b] = [a]

bl = {}
for _ in range(K):
    c, d = map(int, input().split(" "))
    c -= 1
    d -= 1
    if bl.get(c) is not None:
        bl[c].append(d)
    else:
        bl[c] = [d]

    if bl.get(d) is not None:
        bl[d].append(c)
    else:
        bl[d] = [c]

for i in range(N):
    s = uf.get_size(i) - 1

    for b in bl.get(i, []):
        if uf.is_same(i, b):
            s -= 1

    s -= len(fr.get(i, []))
    print(s)


import sys
from itertools import accumulate
n, m, k = [int(i) for i in sys.stdin.readline().split()]

par = list(range(n))
ns = [1 for i in range(n)]

def find(x):
    ls = []
    while x != par[x]:
        ls.append(x)
        x = par[x]
    for l in ls:
        par[l] = x
    return x

def unite(x, y):
    x = find(x)
    y = find(y)
    if x != y:
        par[x] = y
        ns[y] += ns[x]

def is_same(x, y):
    if find(x) == find(y):
        return True
    else:
        return False

ls = [0 for i in range(n)]
friends = [0 for i in range(n-1)]

for i in range(m):
    a, b = [int(i) for i in sys.stdin.readline().split()]
    a -= 1
    b -= 1
    ls[a] -= 1
    ls[b] -= 1
    unite(a, b)

for i in range(n):
    root = find(i)
    ls[i] += ns[root]

for i in range(k):
    c, d = [int(i) for i in sys.stdin.readline().split()]
    c -= 1
    d -= 1
    if is_same(c, d):
        ls[c] -= 1
        ls[d] -= 1

print(" ".join([str(i - 1) for i in ls]))


N,K=map(int, input().split())
for i in range(9000):
    if K**i<=N<K**(i+1):
        print(i+1)

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


from sys import stdin

def get_result(data):
    print(data)
    N, R = data
    return int(N + 100 * (10 - R))

if __name__ == '__main__':
    data = list(map(int, stdin.readline().split(' ')))
    result = get_result(data)
    print(result)


n, r = map(int, input().split())
if n >= 10:
    print(r)
else:
    print(r + 100 * (10 - n))


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

i=0
while True:
    i+=1
    if n<k**i:
        print(i)
        exit()

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


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

ans = 0
t = k**(ans)
while n >= t:
  ans += 1
  t=k**(ans)
if n == 0:
  print(1)
else:
  print(ans)