def kai(a):
    if a == 1:
        return 1
    else:
        return a*kai(a-1)

def L(i, j, x, y):
    return ((x[i] - x[j])**2 + (y[i] - y[j])**2)**0.5

N  = int(input())
x = [0]*N
y = [0]*N
k = kai(N)
l = 0
for n in range(N):
    x[n], y[n] = map(int, input().split())

for X in range(N):
    for Y in range(N):
        if X <= Y:
            continue
        else:
            l += L(X, Y, x, y)

bi = ((N - 1) * k)/((N * (N - 1))/2)

print((l * bi)/k)

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


od = 10**9+7
def comb(n, k):
    c = 1
    for i in range(k):
        c *= n - i
        c %= mod
    d = 1
    for i in range(1, k + 1):
        d *= i
        d %= mod
    return (c * pow(d, mod - 2, mod)) % mod
x,y=map(int,input().split())

ans=0

z=x//2+1

for q in range(z,x+1):
  w=2*q-x
  if w*2+(q-w)==y:
    t=comb(q,w)
    ans+=t

print(ans)

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

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.

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.


import numpy as np
import math

def frac_mod(n, mod, f=1):
    for i in range(1, n + 1):
        f = (f * i) % mod
    return f

def ifrac_mod(n, mod, f_inv=1):
    for i in range(n, 1, -1):
        f_inv = (f_inv * pow(i, mod-2, mod)) % mod
    return f_inv

def cmb_mod(n, r, mod):
    n_frac = frac_mod(n, mod)
    n_r_ifrac = ifrac_mod(n-r, mod)
    r_ifrac = ifrac_mod(r, mod)

    return int((n_frac * n_r_ifrac * r_ifrac) % mod)
mod = 10**9+7
x,y = map(int, input().split())
a = np.array([[1,2], [2,1]])
b = np.array([x,y])
res = np.linalg.solve(a,b)
is_ok = True
if not (res[0].is_integer() and res[1].is_integer()):
    is_ok = False
    ans = 0
x_res = int(res[0])
y_res = int(res[1])
if is_ok:
    ans = cmb_mod(x_res+y_res, x_res, mod)
print(ans)


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

AB=np.array([(a,b) for a,b in zip(A,B)])
AB=AB[np.argsort(AB[:,1])]

AI=np.array([[i,AB[i,0]] for i in range(N)])
AI=AI[np.argsort(AI[:,1])]

sigma=AI[:,0]
ASort=AI[:,1]
BSort=AB[:,1]

g=0
f=0
for i in range(N):
    if ASort[i]>BSort[i]:
        g=1
        break

used=np.array([])
if g==0:
    start=0
    now=sigma[start]
    np.append(used,now)
    while start!=now:
        now=sigma[now]
        np.append(used,now)

    if N==len(used):
        f=1
        for i in range(N-1):
            if BSort[i]>=ASort[i+1]:
                f=0
                break
if f==1 or g==1:
    print("No")
else:
    print("Yes")

Score : 600 points

Problem Statement

Given are two integer sequences of N elements each: A_1,...,A_N and B_1,...,B_N.
Determine if it is possible to do the following operation at most N-2 times (possibly zero) so that, for every integer i from 1 to N, A_i \leq B_i holds:

Choose two distinct integers x and y between 1 and N (inclusive), and swap the values of A_x and A_y.

Constraints

2 \leq N \leq 10^5

1 \leq A_i,B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

3
1 3 2
1 2 3

Sample Output 1

Yes

We should swap the values of A_2 and A_3.

Sample Input 2

3
1 2 3
2 2 2

Sample Output 2

No

Sample Input 3

6
3 1 2 6 3 4
2 2 8 3 4 3

Sample Output 3

Yes


N = int(input())
MOD = 998244353
def func(x):
    a = [23,26]
    out = 1
    for i in range(30):
        if not i in a:
            out = (out*x)%MOD
        x *= x
        x %= MOD
    return out

def func2(x):
    x = bin(x)[2:]
    out = 1
    b = 3
    for i in range(len(x)):
        if x[-1-i] == "1":
            out *= b
            out %= MOD
        b *= b
        b %= MOD
    return out

ans = 0
d = 1
b = 1
for i in range((N//2)):
    ans += d * b
    b *= 2
    b %= MOD
    ans %= MOD
    d = ((N-i)*d)%MOD
    d = (d*func(i+1))%MOD

print((func2(N)-ans*2)%MOD)

Score : 800 points

Problem Statement

Given is a positive even number N.

Find the number of strings s of length N consisting of A, B, and C that satisfy the following condition:

s can be converted to the empty string by repeating the following operation:

Choose two consecutive characters in s and erase them. However, choosing AB or BA is not allowed.

For example, ABBC satisfies the condition for N=4, because we can convert it as follows: ABBC → (erase BB) → AC → (erase AC) → (empty).

The answer can be enormous, so compute the count modulo 998244353.

Constraints

2 \leq N \leq 10^7

N is an even number.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings that satisfy the conditions, modulo 998244353.

Sample Input 1

2

Sample Output 1

7

Except AB and BA, all possible strings satisfy the conditions.

Sample Input 2

10

Sample Output 2

50007

Sample Input 3

1000000

Sample Output 3

210055358


N=int(input())
bandera=False
for i in range(10):
  for j in range(10):
    producto=i*j
    if producto==N:
      bandera=True
if bandera==True:
  print("yes")
else:
  print("no")

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


n = int(input())

revList = [9, 8, 7, 6, 5, 4, 3, 2, 1]
for i in revList:
  if n % i == 0:
    if n/i < 10:
      print("Yes")
      break
else:
  print("No")


n = int(input())

for i in range(9):
    if n%(i+1)==0 and n/(i+1)<10:
        print("Yes")
        break
    elif i==8:
        print("No")


import math

N=int(input())
A=math.sqrt(N)
tmp=float("inf")
for i in range(1,int(A)+1):
	if N%i==0:
		tmp=min(tmp,N//i+i)
print(tmp-2)

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


import math

def solve():
  N = int(input())
  for i in range(math.floor(math.sqrt(N)), 0, -1):
    if N % i != 0: continue
    return i + (N // i) - 2

print(solve())


import numpy as np
import math

a,b,x = map(int,input().split())
taiseki = a*a*b
mizu_height = x / (a*a)
parcent = x/taiseki
print(parcent)
if x/taiseki <= 0.5:
    menseki = mizu_height*a
    a = 2 * menseki / b
    #print(a)
    teihen = np.sqrt(a**2+b**2)
    #print(teihen)
    height = 2*menseki/teihen
    #print(height/b)
    print(90-math.degrees(math.asin(height/b)))

else:
    menseki = mizu_height * a
    daikei_hen = 2*menseki/a - b

    sankaku_b = b - daikei_hen

    sankaku_menseki = a*sankaku_b/2
    daikei_menseki = menseki - sankaku_menseki

    sankaku_teihen = np.sqrt(a**2+sankaku_b**2)
    sankaku_height = 2*sankaku_menseki/sankaku_teihen

    daikei_height = daikei_menseki/sankaku_teihen

    height = daikei_height + sankaku_height

    print(90-math.degrees(math.asin(height/b)))

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


a,b,x=map(int,input().split())
import math
p=2*(a*a*b-x)/a**3
q=(a*b*b)/(2*x)
y=math.atan(p)
u=math.atan(q)
if x>=a**2*b/2:
	print(math.degrees(y))
else:
	print(math.degrees(u))


# coding: utf-8
# Your code here!

import math
import sys

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

al.sort()
fl.sort(reverse=True)

ub = max([a*f for a,f in zip(al, fl)])
lb = 0

while True:
    if ub == lb:
        print(lb)
        sys.exit()
    p = 0
    t = int((ub + lb) / 2)
    for a, f in zip(al, fl):
        p += max(math.ceil(a - t / f), 0)
    if p <= k:
        ub = t
    else:
        lb = t + 1

Score: 500 points

Problem Statement

Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.

In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:

A team should assign one member to each food, and should not assign the same member to multiple foods.

It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.

The score of a team is the longest time it takes for an individual member to finish the food.

Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.

What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

Constraints

All values in input are integers.

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

0 \leq K \leq 10^{18}

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

1 \leq F_i \leq 10^6\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N
F_1 F_2 ... F_N

Output

Print the minimum possible score of the team.

Sample Input 1

3 5
4 2 1
2 3 1

Sample Output 1

2

They can achieve the score of 2, as follows:

Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.

Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.

Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.

They cannot achieve a score of less than 2, so the answer is 2.

Sample Input 2

3 8
4 2 1
2 3 1

Sample Output 2

0

They can choose not to do exactly K sets of training.

Sample Input 3

11 14
3 1 4 1 5 9 2 6 5 3 5
8 9 7 9 3 2 3 8 4 6 2

Sample Output 3

12


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

c=a-b*2

if c<=0:
    print(0)
else:
    print(c)

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


N = int(input())
S = input()
count = 0
for x in range(0,N-1):
    if S[x] == S[x+1]:
        count += 1
ans = len(S) - count
print(ans)

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


n=int(input())
l=list(map(int,input().split()))
ans=0
for i in range(n-2):
    a=l[i]
    for j in range(i+1,n-1):
        b=l[j]
        for k in range(j+1,n):
            c=l[k]
            if a<b+c and b<a+c and c<a+b:
              ans+=1
print(ans)

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


import sys
input = sys.stdin.readline
n=int(input())
l = list(map(int, input().split()))
l=sorted(l)
ans=0
for i in range(n):
  for k in range(i+1,n):
    for _ in range(k+1,n):
      if -l[i]+l[k]>=l[_]:
        continue
      elif l[i]+l[k]<=l[_]:
        break
      else:
        ans+=1
print(ans)


N = int(input())
D = input().split(' ')

D.sort(reverse=True)

count = 0
for i in range(N):
    for j in range(i + 1, N):
        for k in range(j + 1, N):
            if int(D[i]) < int(D[j]) + int(D[k]):
                count += 1
            else:
                break

print(count)


n=int(input())
l=list(map(int,input().split()))
l.sort(reverse=True)
total=0
for i in range(n-2):
  if l[i]<l[i+1]+l[i+2]:
    for j in range(i+1,n-1):
      for k in range(j+1,n):
        if l[i]<l[j]+l[k]:
          total+=1
print(total)


N = int(input())
ans = (N - (N // 2)) / N
print(ans)

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


# 1行目の入力を空白で分割された数値として扱う
n, k = map(int, input().split())
# 2行目の入力を数値のリストとして扱う
h = list(map(int, input().split()))

# 答えのカウンタの準備
cnt = 0

# k以上のhを数える
for i in range(0, n):
    if h[i] >= k:
        cnt += 1

# 答えの出力
print( cnt )

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


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

ans = 0
for h in H :
    if h >= K :
        ans += 1
print(ans)


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

count = dict()

for x in range(1, n+1):
    count[str(x)] = a[x-1]

count_sorted = sorted(count.items(), key=lambda x: x[1])

ans = ''

for x in range(n):
    ans += count_sorted[x][0]
    if x != n-1:
        ans += ' '

print(ans)

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


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

tmpList=QsList[:]
tmpList.sort()

cnt=0
tmp=0
AnsList=QsList[:]
for i in QsList:
  tmp=int(QsList.index(i))+1
  a=int(tmpList.index(i))
  a=int(a)
  AnsList[a]=tmp

print(*AnsList)


N=input()
a=list(map(int, input()))
b=a
c=1
if c<=N:
	d=a[c-1]
	b[d-1]='c'
	c+=1
''.join(b)


from math import *

def next_int():
    return int(input())

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

a, b = next_ints()
n = gcd(a, b)
ans = 1
i = 2
while i*i <= n:
    if n%i == 0:
        ans += 1
        while n%i == 0:
            n //= i
    i += 1
if n != 1:
    ans += 1
print(ans)

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


from math import gcd
a, b = map(int, input().split())
x = gcd(a, b)
z = []
for i in range(2, x):
    flag = True
    if x % i == 0:
        for j in z:
            if i % j == 0:
                flag = False
                break
    if flag == True and x % i == 0:
        z.append(i)
print len(z) + 1


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

while A != 0 and B != 0:
  if A < B:
    B = C
  else:
    A = C
  C = abs(A-B)

i = 2
ans = 1
while C > 1:
  if C%i == 0:
    ans += 1
    while C%i == 0:
      C //= i
  i += 1

print(ans)


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

inf = 10**9

dp = [[inf for _ in range(2**n)]] * m
dp[0][0] = 0

for i in range(m):
    a,b = map(int, input().split())
    d = sum((1<<(i-1)) for i in map(int, input().split()))

    #initialize
    if i==0:
        dp[0][d] = a
        continue

    for j in range(2**n):
        jord = j | d
        print(jord)
        dp[i][jord] = min(dp[i-1][jord], dp[i-1][j] + a)
        print(dp[i][jord])

if dp[m-1][2**n-1] == inf:
    print(-1)
else:
    print(dp[m-1][2**n-1])

Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


import numpy as np

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

dp = [10e9] * (2 ** N)
dp[0] = 0

for i in range(M):
    a, b = map(int, input().split())
    c = map(int, input().split())
    key = np.sum([2**(x-1) for x in c])

    ndp = dp.copy()
    for j in range(2**N):
        if dp[j | key] > ndp[j] + a:
            dp[j | key] = ndp[j] + a

if dp[-1] == np.inf:
  print(-1)
else:
  print(dp[-1])


#142e
N,M = map(int, input().split())

openable_box_and_price = {} #開けられる箱のtaple:値段 なdict

#同じ箱を開けられる鍵は最安値のものを選びつつ、読み込み
for i in range(M):
    a,b = map(int, input().split())
    c = tuple(map(int, input().split()))

    #print(c,":",a)

    if c in openable_box_and_price:
        #print("重複")
        if openable_box_and_price[c] > a:
            #print("安値更新")
            openable_box_and_price[c] = a
    else:
        openable_box_and_price[c] = a

#鍵に番号(0～)を付けるためlist化
key_price = list(openable_box_and_price.values())
key_openable_box = list(openable_box_and_price.keys())

#ある箱を開けられる鍵のリストを作る
key_number = 0
box_and_openable_key = [[] for _ in range(N)]

for openable_boxes in key_openable_box:
    for openable_box in openable_boxes:
        box_and_openable_key[openable_box-1].append(key_number)

    key_number += 1

#すべての箱を開けられる鍵の組み合わせのうち、最安値を求める。
no_ans_flag = 0

#そもそも開けられる鍵が無い箱があったら-1を出力
for openable_key in box_and_openable_key:
    if not openable_key:
        print(-1)
        no_ans_flag = 1
        break

if no_ans_flag != 1:
    def choice_keys(box_number):
        for key_number in box_and_openable_key[box_number]: #箱を開けられる鍵から1個選ぶ
            choiced_keys.append(key_number)
            if len(choiced_keys) != N: #すべての箱に対して鍵を選んでなかったら
                choice_keys(box_number+1) #さらに選ぶ
            else: #すべての箱に対して鍵を選んでたら
                #値段を計算する

                choiced_keys_set = set(choiced_keys) #重複選択している鍵を削除する

                if tuple(choiced_keys_set) not in caluclated_key_set_and_price: #setでは辞書のkeyに使えないので、tuple化
                    #値段計算
                    total_price = 0
                    for choiced_key in choiced_keys_set:
                        total_price += key_price[choiced_key]

                    caluclated_key_set_and_price[tuple(choiced_keys_set)] = total_price

                    #print(choiced_keys,":",choiced_keys_set,":",total_price)

                choiced_keys.pop(-1)

        if len(choiced_keys)!=0:
            choiced_keys.pop(-1)

    caluclated_key_set_and_price = {}
    choiced_keys = []
    choice_keys(0)

    #求めたすべての箱を開けられる鍵の選択肢一覧から最安を選ぶ
    #print(caluclated_key_set_and_price)
    caluclated_key_set_and_price = sorted(caluclated_key_set_and_price.items(), key=lambda x:x[1])
    #print(caluclated_key_set_and_price)
    print(caluclated_key_set_and_price[0][1])


h,w,a,b = map(int, input().split())
if a*2>w or b*2>h:
    print('No')
else:
    ans = [[0 for i in range(w)]for j in range(h)]
    for i in range(h):
        for j in range(w):
            if j<a and i<b:
                ans[i][j]=1
            elif j>=a and i>=b:
                ans[i][j]=1
    for i in range(h):
        print(''.join(map(str,ans[i])))

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

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

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


import sys

class UnionFind:
    def __init__(self, n):
        self.table = [-1] * n

    def _root(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self._root(self.table[x])
            return self.table[x]

    def find(self, x, y):
        return self._root(x) == self._root(y)

    def union(self, x, y):
        r1 = self._root(x)
        r2 = self._root(y)
        if r1 == r2:
            return
        d1 = self.table[r1]
        d2 = self.table[r2]
        if d1 <= d2:
            self.table[r2] = r1
            self.table[r1] += d2
        else:
            self.table[r1] = r2
            self.table[r2] += d1

    def connected_count(self):
        return sum(x < 0 for x in self.table)

n, m, q = list(map(int, input().split()))
uft = UnionFind(n)
hyper_paths = set()

for line in sys.stdin:
    a, b, c = list(map(int, line.split()))
    if c == 1:
        hyper_paths.add((a, b))
        continue
    uft.union(a, b)

for a, b in hyper_paths:
    if uft.find(a, b):
        print('No')
        exit()

cc = uft.connected_count()

min_m = n if len(hyper_paths) > 0 else n - 1
max_m = n - cc + cc * (cc - 1) // 2

print('Yes' if min_m <= m <= max_m else 'No')

Score : 700 points

Problem Statement

Snuke's mother gave Snuke an undirected graph consisting of N vertices numbered 0 to N-1 and M edges.
This graph was connected and contained no parallel edges or self-loops.

One day, Snuke broke this graph.
Fortunately, he remembered Q clues about the graph.
The i-th clue (0 \leq i \leq Q-1) is represented as integers A_i,B_i,C_i and means the following:

If C_i=0: there was exactly one simple path (a path that never visits the same vertex twice) from Vertex A_i to B_i.

If C_i=1: there were two or more simple paths from Vertex A_i to B_i.

Snuke is not sure if his memory is correct, and worried whether there is a graph that matches these Q clues.
Determine if there exists a graph that matches Snuke's memory.

Constraints

2 \leq N \leq 10^5

N-1 \leq M \leq N \times (N-1)/2

1 \leq Q \leq 10^5

0 \leq A_i,B_i \leq N-1

A_i \neq B_i

0 \leq C_i \leq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M Q
A_0 B_0 C_0
A_1 B_1 C_1
\vdots
A_{Q-1} B_{Q-1} C_{Q-1}

Output

If there exists a graph that matches Snuke's memory, print Yes; otherwise, print No.

Sample Input 1

5 5 3
0 1 0
1 2 1
2 3 0

Sample Output 1

Yes

For example, consider a graph with edges (0,1),(1,2),(1,4),(2,3),(2,4). This graph matches the clues.

Sample Input 2

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

Sample Output 2

No

Sample Input 3

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

Sample Output 3

No


import sys
input = sys.stdin.readline

class Node:
    def __init__(self, id):
        self.id = id
        self.parent = None
        self.child_num = 0
        self.is_root = True
        self.grand_parent = False

    def root(self):
        node = self
        while not node.is_root:
            # print(node.id)
            node = node.parent
        return node

def main():
    N, M, Q = map(int, input().split())
    abc = sorted([list(map(int, input().split())) for i in range(Q)], key=lambda x: x[2])

    nodes = [Node(i) for i in range(N)]
    edge_count = 0
    count_rest = True
    ok = True
    for i in range(Q):
        # print(i)
        a, b, c = abc[i]
        if c == 0:# Union-find
            root_a = nodes[a].root()
            root_b = nodes[b].root()
            if root_a != root_b:
                if root_a.child_num > root_b.child_num:
                    root_b, root_a = root_a, root_b
                root_a.child_num += root_b.child_num + 1
                root_b.parent = root_a
                root_b.is_root = False
                edge_count += 1
                if edge_count > M:
                    ok = False
                    break
        else:
            if count_rest:
                rest_node = 0
                for i in range(N):
                    if nodes[i].is_root and nodes[i].child_num == 0:
                        rest_node += 1
                count_rest = False
            if rest_node == 0:
                ok = False
                break
            root_a = nodes[a].root()
            root_b = nodes[b].root()
            if root_a == root_b:
                ok = False
                break
            elif root_a.grand_parent and root_b.grand_parent:
                pass
            elif root_a.grand_parent and not root_b.grand_parent:
                root_b.grand_parent = True
                edge_count += 1
            elif (not root_a.grand_parent) and root_b.grand_parent:
                root_a.grand_parent = True
                edge_count += 1
            else:
                root_a.grand_parent = True
                root_b.grand_parent = True
                edge_count += 2

    has_grand = 0
    for i in range(N):
        if nodes[i].grand_parent:
            has_grand += 1
    yoyu = (has_grand * (has_grand - 1)) // 2

    if edge_count > M:
        ok = False
    elif edge_count < M:
        if edge_count + rest_node - 1 <= M:
            if edge_count + rest_node - 1 + yoyu < M:
                ok = False
        else:
            ok = False

    if not ok:
        print("No")
    else:
        print("Yes")

if __name__ == "__main__":
    main()


W = ['Sunny', 'Cloudy', 'Rainy']
S = input()
if S == W[0]:
  print(W[1])
elif S == W[1]:
  print(W[2])
else:
  print(W[0])

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


S = input()
if S == "Sunny":
  print("Cloudy")
elif S =="Cloudy":
  print("Rainy")
else:
  print("Sunny")


s = input()
m = {"Sunny": "Cloudy", "Cloudy": "Rainy", "Rainy": "Sunny"}

print(m[s])


vals = ['Sunny', 'Cloudy', 'Rainy']

s = input().rstrip()

print(vals[(vals.index(s) + 1) % 3])


S = input()

if S[0] == "S":
    print("Cloudy")
elif S[0] == "C":
    print("Rainy")
else:
    print("Sunny")


S = input()
ans = 'Yes'
for i in range((len(S) + 1) // 2):
  if S[2*i] == 'L' or S[2*i + 1] == 'R':
    ans = 'No'
    break

print(ans)

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

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

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


s=input()

i=0

for x in range(len(s)):
    if(i%2==1):
        if(s[i] =='R' or 'U' or 'D'):
            flug=1
    else:
        if(s[i] =='L' or 'U' or 'D'):
            flug=1

if(flug!=1):
    print("No")
else:
    print("Yes")


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

p = [k - q] * n

a = []
for _ in range(q):
    a.append(int(input()))

for i in range(q):
    p[a[i]-1] += 1

for i in range(n):
    if p[i] <= 0:
        print("No")
    else:
        print("Yes")

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


from collections import deque
N,K,Q=map(int,input().split())
ls=[int(input())-1 for i in range(Q)]
que=deque(ls)
co=[0 for i in range(N)]
for j in range(Q):
  co[que.popleft()]+=1
for i in co:
  if i>Q-K:
    print("Yes")
  else:
    print("No")


import numpy as np

ninzu, k, seikaisu = map(int, input().split())

sankasya = np.array([k] * ninzu)

for i in range(seikaisu):
    sankasya = sankasya - 1
    seikaisya = int(input()) - 1
    sankasya[seikaisya] = sankasya[seikaisya] + 1

for point in sankasya:
    if point > 0:
        print('Yes')
    else:
        print('No')


# 190915 C
if __name__ == "__main__":
    N = list(map(int,input().split()))
    K = N[1]
    Q = N[2]
    N = N[0]
    A = [0] * N
    maxp = 0
    for i in range(Q):
        tmpi = int(input())
        A[tmpi-1] += 1

    for i in range(N):
        if K - (Q - A[i]) <= 0:
            print("No")
        else:
            print("Yes")


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
value = 0
for i in range(N):
  value += B[A[i]-1]
  if i > 0 and A[i] == A[i-1]+1:
    value += C[A[i-1]-1]
print(value)

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

class BIT:
    '''
    a[1]~a[n]の数列を想定
    '''

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

    def add(self, index, x):
        '''
        a[index]にxを加算
        '''
        while index <= self.size:
            self.tree[index] += x
            index += index & (-index)

    def sum(self, index):
        '''
        a[1]~a[index]の和
        '''
        s = 0
        while index:
            s += self.tree[index]
            index -= index & (-index)
        return s

    def search(self, value):
        '''
        sum(index)>=value を満たす最小のindex
        sum(n)<value のとき n+1 を返す
        '''
        i = 0
        s = 0
        step = 1 << (self.size.bit_length() - 1)
        while step:
            if i + step <= self.size and s + self.tree[i + step] < value:
                i += step
                s += self.tree[i]
            step //= 2
        return i + 1

def index_sort(A,reverse=False):
    x = []
    for i,a in enumerate(A):
        x.append((a,i))
    if reverse:
        return sorted(x, key=lambda x: -x[0])
    else:
        return sorted(x, key=lambda x: x[0])

N = I()
P = III()

bit = BIT(N)
x = index_sort(P,True)

ans = 0
for i in range(N):
    index = x[i][1]
    if index>=1:
        L = bit.sum(index)
    else:
        L = 0
    wi = bit.search(L-1) if L>=2 else 0
    xi = bit.search(L) if L>=1 else 0

    R = bit.sum(N)-bit.sum(index+1)
    yi = bit.search(L+1)
    zi = bit.search(L+2)

    ci = (xi-wi)*(yi-index-1) + (index+1-xi)*(zi-yi)
    ans += ci*x[i][0]
    bit.add(index+1, 1)

print(ans)

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


s = list(input())
t = list(input())

count = 0

for i in range(3):
    if s[i] == t[i]:
        count = count + 1

print(count)

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


a,b = map(int,input().split())
count = 0
if a >= b:
    print(1)
b = b - a
count +=1
while b > 0:
    b = b - (a-1)
    count += 1
print(count)

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


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

if math.ceil(B/A)==1:
  print(1)

else:
  print(B//A+1)


a,b=map(int,input().split())
total=1
count=0

for i in range(100):
  if total<b:
    total+=a-1
    count+=1
print(count)


List = list(map(int, input().split()))
A = List[0]
B = List[1]
ans = B/A
if ans <1:
    print(1)
elif B%A==0:
    print(int(ans))
else:
    print(int(ans)+1)


A, B = map(int, input().split())
if B <= 1:
    answer = 0
else:
    answer = -(-(B-1) // (A-1))
print(answer)


n = int(input())
h = list(map(int,input().split()))
A = []
ans = 0
for i in range(n-1):
    if h[i]>=h[i+1]:
        ans += 1

print(ans-1)

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


n = int(input())
h = list(map(int, input().split()))
answer = -1#これなに
m = 0#カウントするやつやね
for i in range(n-1):
    if h[i] >= h[i+1]:
        m += 1
    else:
        answer = max(answer,m)
        m = 0
answer = max(answer,m)
print(answer)


import copy
n = int(input())
r_L = list(map(int,input().split()))
l_L = copy.deepcopy(r_L)
l_L.reverse()

r_ans,l_ans = 0,0
r_ans_L,l_ans_L = [],[]

for val in range(n-1):
    if r_L[val] >= r_L[val+1]:
        r_ans += 1
    else:
        r_ans_L.append(r_ans)
        r_ans = 0

l_ans_L.append(l_ans)
r_ans_L.append(r_ans)

print(max(max(l_ans_L),max(r_ans_L)))


N = int(input())
masu = list(map(lambda x: int(x), input().split()))

count = 0
max_count = 0

for i in range(N - 1):
    if (masu[i] >= masu[i + 1]):
        count += 1
    else:
        if max_count < count:
            max_count = count
        count = 0

if count == N - 1:
    print(count)
else:
    print(max_count)


Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

N is an integer satisfying 1 \leq N \leq 10^9.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


S=float(input())
#N=list(map(int,input().split()))
ans=(S-1)*S/2
print(int(ans))


n = int(input())
ans = n * (n-1) // 2
print(ans)


n = int(input())
tmp = 0
max = 0
for i in range(n):
    max = max + i
print(max)


# 休憩review
# League
from collections import deque
N = int(input())
G = [[] for i in range(N**2+1)]
for i in range(N):
    a = list(map(int, input().split()))
    for j in range(1, N-1):
        _from, _to = a[j-1], a[j]
        G[N*min(i+1, _from)-N+max(i+1, _from)
          ].append(N*min(i+1, _to)-N+max(i+1, _to))

In = [0 for i in range(N**2+1)]  # In[node] = node に入る入次数
for i in range(1, N**2+1):
    for node in G[i]:
        In[node] += 1

stack = deque()
for i in range(1, N**2+1):
    if In[i] == 0:
        stack.append(i)  # stack := 入次数が0になった点を入れておく

Removed = [False for i in range(N**2+1)]  # 考慮されたか
cnt = [1 for i in range(N**2+1)]

while stack:
    x = stack.popleft()
    Removed[x] = True
    for node in G[x]:
        In[node] -= 1
        if In[node] == 0:
            cnt[node] += cnt[x]
            stack.append(node)

all_checked = all(Removed[node] == True for node in range(1, N**2+1))
if all_checked:
    answer = max(cnt)
    print(answer)
    exit()
print(-1)

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

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

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


#######################################
prime = 10**9+7

def sowa(num):
  return int((1+num)*num/2)
#######################################
n,k = map(int, input().split())
a = list(map(int, input().split()))

tento1 = [sum([1 if a[i]>a[j] else 0 for j in range(i,n)]) for i in range(n-1)]
tento2 = [sum([1 if a[i]>a[j] else 0 for j in range(n)]) for i in range(n)]

ret = ((sum(tento1)%prime) *(k%prime) %prime) + ((sum(tento2)%prime) *(sowa(k-1) %prime)%prime)
print(ret%prime)

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

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

Sample Output 3

185297239

Be sure to print the output modulo 10^9 + 7.


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

ans = 0
for i in list_a:
  ans += 1/i

print(1/ans)

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


n=int(input())
l=list(map(int,input().split()))
l=list(map(lambda x:1/x,l))

a=sum(l)
ans=1/a

print(ans)


import heapq

N = int(input())
V = [int(x) for x in input().split()]

heapq.heapify(V)

for i in range(N-1):
    a= heapq.heappop(V)
    b= heapq.heappop(V)
    c=(a+b)/2
    heapq.heappush(V,c)

ans = heapq.heappop(V)
print(ans)

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


import sys
import bisect

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7
alphabet = [chr(i) for i in range(97, 97 + 26)]

def resolve():
    S = input()
    T = input()

    n = len(S)
    m = len(T)

    idx = [[] for _ in range(26)]
    for i in range(n):
        idx[alphabet.index(S[i])].append(i)

    for i in range(n):
        idx[alphabet.index(S[i])].append(i + n)

    res = 0
    pos = 0
    for i in range(m):
        c = alphabet.index(T[i])
        if len(idx[c]) == 0:
            print(-1)
            break
        pos = idx[c][bisect.bisect_left(idx[c], pos)] + 1
        if pos >= n:
            pos -= n
            res += n
    else:
        res += pos
        print(res)

if __name__ == '__main__':
    resolve()

Score : 500 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.

Let s' be the concatenation of 10^{100} copies of s. t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s').

Notes

A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net, c, and contest.

Constraints

1 \leq |s| \leq 10^5

1 \leq |t| \leq 10^5

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If there exists an integer i satisfying the following condition, print the minimum such i; otherwise, print -1.

Sample Input 1

contest
son

Sample Output 1

10

t = son is a subsequence of the string contestcon (the first 10 characters in s' = contestcontestcontest...), so i = 10 satisfies the condition.

On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s'), so i = 9 does not satisfy the condition.

Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10.

Sample Input 2

contest
programming

Sample Output 2

-1

t = programming is not a substring of s' = contestcontestcontest.... Thus, there is no integer i satisfying the condition.

Sample Input 3

contest
sentence

Sample Output 3

33

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return list(map(list, input().split()))
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#A
def A():
    d = {"Sunny":1 , "Cloudy":2, "Rainy":0}
    a = ["Sunny", "Cloudy", "Rainy"]
    print(a[d[input().rstrip()]])
    return

#B
def B():
    s = S()
    for i, si in enumerate(s):
        if i % 2:
            if si == "R":
                print("No")
                return
        else:
            if si == "L":
                print("No")
                return
    print("Yes")
    return

#C
def C():
    n, k, q = LI()
    d = [0] * n
    for _ in range(q):
        a = II() - 1
        d[a] += 1
    for a in d:
        if k - (q - a) > 0:
            print("Yes")
        else:
            print("No")
    return

#D
def D():
    n,m = LI()
    a = LI()
    q = []
    for ai in a:
        heappush(q, -ai)
    for _ in range(m):
        heappush(q, heappop(q) / 2)
    ans = 0
    while q:
        ans += int(-heappop(q))
    print(ans)
    return

#E
def E():
    s = S()
    t = S()
    d = defaultdict(list)
    for i,si in enumerate(s):
        d[si].append(i)
    if d[t[0]] == []:
        print(-1)
        return
    before = d[t[0]][0]
    ans = 0
    for ti in t[1:]:
        if d[ti] == []:
            print(-1)
            return
        a = d[ti]
        index = bisect_right(a, before)
        if index == len(a):
            ans += 1
            before = a[0]
        else:
            before = a[index]
    print(ans * len(s) + before + 1)
    return

#F
def F():
    return

#Solve
if __name__ == '__main__':
    E()


s=input().rstrip()
x=list(s)
t=input().rstrip()
y=list(t)
for i in range(0,len(y)):
    if y[i] not in x:
        print(-1)
        break;
else:
    C=0;
    D=0;
    for i in range(0,len(y)):
        T=y[i]
        CC=x[C:len(x)]
        if T in CC:
            V=CC.index(T)
            C=V+C;
        else:
            D+=1;
            V=x.index(T)
            C=V;
    print(D*len(x) + C+1)


L, R = map(int, input().split())
dp = [[[[0]*2 for _ in range(2)] for _ in range(2)] for _ in range(65)]
dp[0][0][0][0] = 1
MOD = 10**9+7

for i in range(64):
    Li = (L>>(63-i))&1
    Ri = (R>>(63-i))&1

    for j in range(2):
        for k in range(2):
            for l in range(2):
                for x in (range(2) if j else range(Li, 2)):
                    for y in range(2 if k else Ri+1):
                        if x==1 and y==0:
                            continue

                        if l==0 and x==0 and y==1:
                            continue

                        dp[i+1][j|(x>Li)][k|(y<Ri)][l|(x==1 and y==1)] += dp[i][j][k][l]
                        dp[i+1][j|(x>Li)][k|(y<Ri)][l|(x==1 and y==1)] %= MOD

ans = 0

for i in range(2):
    for j in range(2):
        for k in range(2):
            ans += dp[-1][i][j][k]
            ans %= MOD

print(ans)

Score : 600 points

Problem Statement

Given are integers L and R. Find the number, modulo 10^9 + 7, of pairs of integers (x, y) (L \leq x \leq y \leq R) such that the remainder when y is divided by x is equal to y \mbox{ XOR } x.

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

1 \leq L \leq R \leq 10^{18}

Input

Input is given from Standard Input in the following format:

L R

Output

Print the number of pairs of integers (x, y) (L \leq x \leq y \leq R) satisfying the condition, modulo 10^9 + 7.

Sample Input 1

2 3

Sample Output 1

3

Three pairs satisfy the condition: (2, 2), (2, 3), and (3, 3).

Sample Input 2

10 100

Sample Output 2

604

Sample Input 3

1 1000000000000000000

Sample Output 3

68038601

Be sure to compute the number modulo 10^9 + 7.


s = input()
n = len(s)

ans = n
b = 1
for i in range(1, n):
    if s[i-1] == s[i]:
        b += 1
    else:
        ans -= (b+1) // 3
        if b % 3 == 2:
            b = 0
        else:
            b = 1
    # print(i,ans,b)

ans -= (b+1) // 3

print(ans)

Score : 300 points

Problem Statement

Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:

There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).

Here S_1S_2...S_K represents the concatenation of S_1,S_2,...,S_K in this order.

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum positive integer K that satisfies the condition.

Sample Input 1

aabbaa

Sample Output 1

4

We can, for example, divide S into four strings aa, b, ba, and a.

Sample Input 2

aaaccacabaababc

Sample Output 2

12


s = input()
si = s[0]
ans = 1
for i in range(len(s)):
    if s[i] != si:
        ans += 1
        si = s[i]
    else:
        si = s[i:i + 2]
print(ans)


import sys, math
from collections import deque

readline = sys.stdin.readline

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

print(max(a+b, a-b, a*b))

Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

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

Sample Input 2

1 -33

Sample Output 2

34

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

Sample Input 3

13 3

Sample Output 3

39

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


import sys
input = sys.stdin.readline

n = int(input())
sn = [input().strip('\n') for _ in range(n)]

mod = 10**5 + 7
hs = [[0, ''] for _ in range(mod)]

def hypo(s, Mod):
    h_num = 1
    for i in s:
        h_num = h_num * ord(i) % Mod
    return h_num

for s in sn:
    s = ''.join(sorted(s))
    h = hypo(s, mod)
    if hs[h][0] > 0:
        i = 0
        while True:
            if h + i >= mod :
                h = 0
                i = 0
            if hs[h+i][1] == s:
                hs[h+i][0] += 1
                break
            i += 1
    else:
        hs[h][0] += 1
        hs[h][1] += s

ans = 0
for j, t in hs:
    if j >= 2:
        ans += j * (j-1) / 2

print(int(ans))

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


n = int(input())
s = ["".join(sorted(str(input()))) for i in range(n)]
d = {}
ans = 0
for i in s:
    if i not in d:
        d[i] = 0
    else:
        d[i] += 1
        ans += d[i]
print(ans)


n=int(input())
s=[]
for i in range(n):
    x=input()
    y=[]
    for i in x:
        y.append(i)
    y.sort()
    s.append(''.join(y))

d=dict()

for i in range(n):
    if s[i] not in d.keys():
        d[s[i]]=1
    else:
        d[s[i]]+=1
ans=0
for v in d.values():
    ans+=v*(v-1)/2
print(int(ans))


import math
n = int(input())
l = [input() for _ in range(n)]
l = [sorted([j for j in i]) for i in l]
l = ["".join(i) for i in l]
al = list(set(l))
ans_dict = {}
for i in l:
    if i in ans_dict:
        ans_dict[i]+=1
    else:
        ans_dict[i] = 1
    ans = 0
for i in al:
    if ans_dict[i] > 1:
        ans += (math.factorial(ans_dict[i])//math.factorial(2))

print(ans)


N = int(input())

lst = []

for i in range(N):
    lst.append("".join(sorted(list(input()))))

d={}
count = 0

for i in lst:
  if not i in d:
    d[i] = 1
    continue
  else:
    d[i] = d[i] + 1
    count = count + d[i]-1

print(count)


# -*- coding: utf-8 -*-
N = int(raw_input())
cnt = 0
dic = {}

for _ in xrange(N):
	rs = ''.join(sorted(raw_input()))

	if rs in dic:
		cnt += dic[rs]
		dic[rs] += 1
	else:
		dic[rs] = 1
print cnt


'''
rows , days = map(int,input().split())
total = 0
arr2 = [[] for _ in range(days)]

for i in range(rows):
    day , r = list(map(int,input().split()))
    if day <= days:
        arr2[day].append(r)

print(arr2)
'''

#標準入力受け取り
N, M = list(map(int, input().split()))
jobs = [[] for _ in range(M)]

for i in range(N):
    d, r = list(map(int, input().split()))
    if d-1 < M:
        jobs[d-1].append(r)

print(jobs)
#解法
rewards = 0
li = []
for i in range(M):
    #候補をリストに追加(給料が間に合うもの仕事が一日ごとに増える)
    li.extend(jobs[i])
    if len(li) >0:
        #最大値を求める(給料が高いバイトをしたい)
        reward = max(li)
        rewards += reward
        #使った値は取り除く(同じバイトはNGのため)
        li.remove(reward)

print(rewards)

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


# 2019 8/10
# ABC137 D Summer Vacation

info = []
reword = 0
day = 0

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

for i in range(N):
    A, B = map(int, input().split())
    info.append([B, A])

info.sort(reverse=True)
print(info)

for i in range(N):
    if day > M:
        break

    if info[i][1] + day <= M:
        reword += info[i][0]
        day += 1

print(reword)


import math
import sys

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

print(max(0,C - (A-B)))

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


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

X1 = B
X2 = C

move = min(A - B, C)

X1 += move
X2 -= move

print(X2)


a, b, c = (int(x) for x in input().split(' '))

d = c - (a - b)

if d > 0:
    print(d)
else:
    print(0)


A, B, C = map(lambda x: int(x), input().split(' '))
if B + C > A:
    print(B + C - A)
else:
    print(B + C)


n = input()
digit_n = len(str(n))
n = int(n)
ans = 0

if digit_n % 2 == 0:
    for i in range(digit_n // 2):
        ans += 9 * 10 ** (i * 2)

else:
    if digit_n != 1:
        for i in range((digit_n - 1) // 2):
            ans += 9 * 10 ** (i * 2)
        hasuu = int(str(n)[1:])
        ans += hasuu + 1

    else:
        ans = n

print(ans)

Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


n = int(input())
count = 0

while n > 0:
    if len(str(n)) % 2 == 0:
        n -= 1
        continue

    count += 1
    n -= 1

print(count)


S = input()
#dp_roop[position] = roop
dp_roop = {}
dp_mod2 = {}

Result = [0] * len(S)
counted = set()

def roop_from(position):
    head = []
    visited = set()
    while position not in visited:
        head.append(position)
        visited.add(position)
        #print(position, head, visited)
        if S[position] == "R":
            position += 1
        else:
            position -= 1

    roop = head[head.index(position):]
    return head, roop

def register(head, roop):
    for i, position in enumerate(head):
        if position not in counted:
            mod2 = (len(head) + i) % 2
            Result[roop[mod2]] += 1
            counted.add(position)

for i in range(0, len(S)):
    if i not in counted:
        #print(i)
        head, roop = roop_from(i)
        register(head, roop)

print(*Result, sep=" ")

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

0 3 3 0 0 0 1 1 0 2 2 0

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


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

# 約数の全列挙
def divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    divisors.sort(reverse = True)  # ソート
    return divisors

ansList = divisors(sumA)
ans = 1

for div in ansList :
    count = 0
    for a in A :
        b = a % div
        count += min(b, div - b)

    if count <= 2 * K :
        ans = div
        break

print(ans)

Score : 500 points

Problem Statement

We have a sequence of N integers: A_1, A_2, \cdots, A_N.

You can perform the following operation between 0 and K times (inclusive):

Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of A after the operations. Here a positive integer x divides an integer y if and only if there exists an integer z such that y = xz.

Constraints

2 \leq N \leq 500

1 \leq A_i \leq 10^6

0 \leq K \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_{N-1} A_{N}

Output

Print the maximum possible positive integer that divides every element of A after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

7 will divide every element of A if, for example, we perform the following operation:

Choose i = 2, j = 1. A becomes (7, 21).

We cannot reach the situation where 8 or greater integer divides every element of A.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose i = 2, j = 1. A becomes (2, 6).

Choose i = 2, j = 1. A becomes (1, 7).

Choose i = 2, j = 1. A becomes (0, 8).

Choose i = 2, j = 1. A becomes (-1, 9).

Choose i = 1, j = 2. A becomes (0, 8).

Then, 0 = 8 \times 0 and 8 = 8 \times 1, so 8 divides every element of A. We cannot reach the situation where 9 or greater integer divides every element of A.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5


a,b = map(int,input().split())
print((a+b)//2 if (a+b)%2 == 0 or a == b else "IMPOSSIBLE")

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

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

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


A = int(input())
B = int(input())
K = (A+B)//2
if type(K) is int:
  print(K)
else:
  print("Impossible")


a = input('A: ')
b = input('B: ')
c = int(a + b)

def judge_int():
    if c % 2 == 0:
        return c/2
    elif c % 2 != 0:
        return "IMPOSSIBLE"

print(judge_int())


n,m=[int(i) for i in input().split()]
if (n+m)%2==0:
  print((n+m)//2)
else:
  print("IMPOSSIBLE")


import copy

def swap(array, i,j,tar1,tar2):
  tmp = tar1
  array[i] = tar2
  array[j] = tmp
#  print(array)
  return array

def orderd(array):
  orderd_array = sorted(array)
#  print(array,orderd_array)
  for i in range(len(array)):
    if not orderd_array[i]==array[i]:
      return False
  return True

N = int(input())
P = list(map(int,input().split()))
# print(P)
ans = "NO"
flg = False
for i in range(N):
  for j in range(i,N):
    Pi = copy.copy(P)
    Pi = swap(Pi,i,j,Pi[i],Pi[j])
    if orderd(Pi):
      ans = "YES"
      flg=True
      break
  if flg:
    break
#print(P)
print(ans)

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy,copy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
    n=INT()
    p=LIST()

    lis=[]
    l=1
    for i in range(1,n):
        if p[i] < p[i-1]:
            if l!=1:
                lis.append(l)
        else:
            l+=1

    if l!=1:
        lis.append(l)

    #print(lis)
    if len(lis)==1:
        print('YES')
    else:
        print('NO')

if  __name__=='__main__':
    main()


n = int(input())
cities = list(map(int,input().split()))
braves = list(map(int,input().split()))
braves.append(0)
count = 0
for i in range(n+1):
  c = min(braves[i],cities[i])
  count += c
  if i != n:
    braves[i+1] += braves[i] - c
print(count)

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


from sys import stdin

def fetch_one_line():
    return stdin.readline().rstrip()

def fetch_int_input():
    return [int(s) for s in fetch_one_line().split()]

def fetch_inputs(times):
    return [fetch_one_line() for _ in range(times)]

def fetch_int_inputs(times):
    return [[int(s) for s in fetch_one_line()] for _ in range(times)]

def fetch_ints_inputs(times):
    return [fetch_int_input() for _ in range(times)]

ipt = fetch_one_line()
DIVIDE_NUM = 13
remainds = [[0 for _ in range(DIVIDE_NUM)]]
remainds[0][0] = 1

def transrate(matrix):
    return list(map(list, zip(*matrix)))

def make_remind(latest_remind, digit):
    tmp_remind = [[latest_remind[(j - (i * (digit % 13))) % 13] for j in range(DIVIDE_NUM)]
            for i in range(10)]

    return [sum(t) for t in transrate(tmp_remind)]

for idx, s in enumerate(ipt[::-1]):
    if s == "?":
        digit = pow(10, idx)
        remainds.append(make_remind(remainds[-1], digit))
    else:
        int_s = int(s)
        digit = pow(10, idx)
        move = (int_s % 13) * (digit % 13)
        new_remaind = [remainds[-1][(i - move) % 13] for i in range(DIVIDE_NUM)]
        remainds.append(new_remaind)

print(remainds[-1][5] % (pow(10, 9) + 7))

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of integers satisfying the condition, modulo 10^9+7.

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888


import sys
input=sys.stdin.readline

s = int(input())
import math
y3 = math.ceil(s//(10**9))
x3 = abs((10**9)*y3-s)

print("0 0 %d %d %d %d" %(10**9, 1, x3, y3))

Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


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

dic = {}
for i in range(N):
    a = A[i]
    v = dic.get(a, None)
    if v is None:
        dic[a] = [i]
    else:
        v.append(i)

result = []
result_dic = {}
result_dic_index = {}
count = 0
loop = 0
while count < K:
    index = 0
    if count != 0:
        if result:
            a = result[index]
            v = dic.get(a)
            next_i = v[0]
            index = next_i + 1
            result.clear()
    while index < N:
        a = A[index]
        v = dic.get(a)
        next_i = -1
        for i in v:
            if i > index:
                next_i = i
                break
        if next_i == -1:
            result.append(a)
            index += 1
        else:
            index = next_i + 1
    tu = tuple(result)
    t = result_dic.get(tu, None)
    if t is None:
        result_dic[tu] = count
        result_dic_index[count] = tu
    else:
        loop = count
        break
    count += 1

answers = None
if loop == 0:
    answers = tu
else:
    index = (K - 1) % loop
    answers = result_dic_index[index]

for answer in answers:
    print(answer, end=" ")
print()

Score : 700 points

Problem Statement

We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}).
Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.

Snuke has an integer sequence s, which is initially empty.
For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:

If s does not contain X_i: add X_i to the end of s.

If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.

Find the elements of s after Snuke finished the operations.

Constraints

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

1 \leq K \leq 10^{12}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 \cdots A_{N-1}

Output

Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.

Sample Input 1

3 2
1 2 3

Sample Output 1

2 3

In this case, X=(1,2,3,1,2,3).
We will perform the operations as follows:

i=0: s does not contain 1, so we add 1 to the end of s, resulting in s=(1).

i=1: s does not contain 2, so we add 2 to the end of s, resulting in s=(1,2).

i=2: s does not contain 3, so we add 3 to the end of s, resulting in s=(1,2,3).

i=3: s does contain 1, so we repeatedly delete the element at the end of s as long as s contains 1, which causes the following changes to s: (1,2,3)→(1,2)→(1)→().

i=4: s does not contain 2, so we add 2 to the end of s, resulting in s=(2).

i=5: s does not contain 3, so we add 3 to the end of s, resulting in s=(2,3).

Sample Input 2

5 10
1 2 3 2 3

Sample Output 2

3

Sample Input 3

6 1000000000000
1 1 2 2 3 3

Sample Output 3

s may be empty in the end.

Sample Input 4

11 97
3 1 4 1 5 9 2 6 5 3 5

Sample Output 4

9 2 6


Score : 100 points

Problem Statement

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

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

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

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

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


import math
n,d=map(int,input().split())
ans=math.ceil(n/(2*d+1))
print(ans)

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


n=int(input())
a=[]
for i in range(n):
    a.append(int(input()))
b=max(a)
c=a.index(b)
a.pop(c)
d=max(a)
for i in range(n):
    if (i==c):
        print('{0}'.format(d))
    else:
        print('{0}'.format(b))

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


n = int(input())
a = []
for i in range(0, n):
    a.append((int(input()), i))
a.sort()
a.reverse()
for i in range(0, n):
    num = 0
    while a[num][1] == i:
        num += 1
    print(a[num][0])