H,W = map(int, input().split())
N = int(input())
a = list(map(int, input().split()))
i = 0
s = ["" for j in range(H)]
for y in range(H):
    for x in range(W):
        if x != 0: s[y] = s[y] + " "
        s[y] = s[y] + str(i+1)
        a[i] = a[i] - 1
        if a[i] == 0:
            i = i+1
    if y%2 == 0 : print(s[y])
    else:
        print(" ".join(s[y].split()[::-1]))

Score : 400 points

Problem Statement

We have a grid with H rows and W columns of squares.
Snuke is painting these squares in colors 1, 2, ..., N.
Here, the following conditions should be satisfied:

For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.

For each i (1 ≤ i ≤ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

1 ≤ H, W ≤ 100

1 ≤ N ≤ H W

a_i ≥ 1

a_1 + a_2 + ... + a_N = H W

Input

Input is given from Standard Input in the following format:

H W
N
a_1 a_2 ... a_N

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}

Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color 1 are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

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

Sample Input 3

1 1
1
1

Sample Output 3

1


n, m = map(int, input().split())
root = [[False]*n for _ in range(2)]

for i in range(m):
    a, b = map(int, input().split())
    if a==1:
        root[0][b-1] = True
    if b==n:
        root[1][a-1] = True
for j in range(n):
    if root[0][j]:
        if root[1][j]:
            print('POSSIBLE')
            exit(0)
print('IMPOSSIBLE')

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

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

If i \neq j, (a_i, b_i) \neq (a_j, b_j).

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.

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.


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

ans = False
# cnt (0, 1, 2, ..., N - 1)
cnt = [0 for i in range(0, N)]
for _ in range(M):
    a, b = map(int, input().split())
    if a == 1:
        cnt[b] += 1
        if cnt[b] == 2:
            ans = True
            break
    elif b == N:
        cnt[a] += 1
        if cnt[a] == 2:
            ans = True
            break

if ans:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")


N, M = [x for x in input().split()]
E = [[] for x in range(N+1)]
visited = set()

for i in range(M):
    A, B = [x for x in input().split()]
    E[A].append(B)
    E[B].append(A)

if E[1] & E[N]:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")


K=int(input())
K1=K//50
K2=K%50

answer_list=[]
for i in reversed(range(50-K2)):
  answer_list.append(i)
for i in range(K2):
  answer_list.append(50-i)
#print(answer_list)

for i in range(50):
  answer_list[i]+=K1

print(answer_list)

Score : 600 points

Problem Statement

We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller.

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1.

It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations.

You are given an integer K. Find an integer sequence a_i such that the number of times we will perform the above operation is exactly K. It can be shown that there is always such a sequence under the constraints on input and output in this problem.

Constraints

0 ≤ K ≤ 50 \times 10^{16}

Input

Input is given from Standard Input in the following format:

K

Output

Print a solution in the following format:

N
a_1 a_2 ... a_N

Here, 2 ≤ N ≤ 50 and 0 ≤ a_i ≤ 10^{16} + 1000 must hold.

Sample Input 1

0

Sample Output 1

4
3 3 3 3

Sample Input 2

1

Sample Output 2

3
1 0 3

Sample Input 3

2

Sample Output 3

2
2 2

The operation will be performed twice: [2, 2] -> [0, 3] -> [1, 1].

Sample Input 4

3

Sample Output 4

7
27 0 0 0 0 0 0

Sample Input 5

1234567894848

Sample Output 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425


n=int(input())
a=list(map(int,input().split()))
inf = 1000000000000000000
ans = inf
def okay(nd, debug=False):
    tot = 0
    dp = [ [ -1 for i in range(n) ] for j in range(n+1) ]
    dp[0][0] = 0
    for i in range(n):
        bl,br,ba=0,nd,inf
        while bl <= br:
            bm = (bl + br) // 2
            if a[i] - bm * n + (nd - bm) < n:
                ba = bm
                br = bm - 1
            else:
                bl = bm + 1
        if debug:
            print(i, ba)
        for j in range(n):
            if dp[i][j] == -1:
                continue
            for k in range(n):
                tdp = dp[i][j] + ba + k
                if tdp > nd:
                    continue
                if dp[i+1][tdp % n] == -1 or tdp < dp[i+1][tdp % n]:
                    dp[i+1][tdp % n] = tdp
    if dp[n][nd % n] == -1:
        return False
    return dp[n][nd % n] <= nd
for sft in range(0,n):
    l,r,ta=0,inf,inf
    while l <= r:
        m = (l + r) // 2
        if okay(m*n + sft):
            ta = m*n + sft
            r = m - 1
        else:
            l = m + 1
    # print(sft, ta)
    ans=min(ans,ta)
# okay(1234567894848, True)
# okay(ans, True)
print(ans)

Score : 600 points

Problem Statement

We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. (The operation is the same as the one in Problem D.)

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1.

It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations.

You are given the sequence a_i. Find the number of times we will perform the above operation.

Constraints

2 ≤ N ≤ 50

0 ≤ a_i ≤ 10^{16} + 1000

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the number of times the operation will be performed.

Sample Input 1

4
3 3 3 3

Sample Output 1

0

Sample Input 2

3
1 0 3

Sample Output 2

1

Sample Input 3

2
2 2

Sample Output 3

2

Sample Input 4

7
27 0 0 0 0 0 0

Sample Output 4

3

Sample Input 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425

Sample Output 5

1234567894848


import math

n, k = map(int, input().split())
array = [int(x) for x in input().split()]

res = math.gcd(array[0], array[1])

for i in array[2:]:
    res = math.gcd(res, i)
print("POSSIBLE" if k%res==0 and max(array) >= k else "IMPOSSIBLE")

Score : 300 points

Problem Statement

There is a box containing N balls. The i-th ball has the integer A_i written on it.
Snuke can perform the following operation any number of times:

Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.

Determine whether it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq K \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

If it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written, print POSSIBLE; if it is not possible, print IMPOSSIBLE.

Sample Input 1

3 7
9 3 4

Sample Output 1

POSSIBLE

First, take out the two balls 9 and 4, and return them back along with a new ball, abs(9-4)=5.
Next, take out 3 and 5, and return them back along with abs(3-5)=2.
Finally, take out 9 and 2, and return them back along with abs(9-2)=7.
Now we have 7 in the box, and the answer is therefore POSSIBLE.

Sample Input 2

3 5
6 9 3

Sample Output 2

IMPOSSIBLE

No matter what we do, it is not possible to have 5 in the box. The answer is therefore IMPOSSIBLE.

Sample Input 3

4 11
11 3 7 15

Sample Output 3

POSSIBLE

The box already contains 11 before we do anything. The answer is therefore POSSIBLE.

Sample Input 4

5 12
10 2 8 6 4

Sample Output 4

IMPOSSIBLE


# -*- coding: utf-8 -*-
N, A = map(int, input().split())
tmp = input()
ary = [int(a) for a in tmp.split()]

maximum = max(ary)

def gcd(a, b):
    if a < b:
        a, b = b, a
    if b == 0:
        return a
    c = a % b
    return gcd(b, c)

g = None
for a in ary:
    if g is None:
        g = a
        continue
    g = gcd(g, a)

if A % g == 0 and A <= maximum:
    print("POSSIBLE")
else:
    print("IMPOSSIBLE")


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

cum = [0]*(N+1)
for i in range(1, N+1):
    cum[i] = cum[i-1] + a[i-1]

ret = 10**10
for i in range(1, N):
    x = cum[i]
    y = cum[-1] - x
    if abs(x-y) < ret:
        ret = abs(x-y)

print(ret)

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

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

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


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

A_r = A[::-1]

cumsum_A = np.cumsum(A)
cumsum_A_r = np.cumsum(A_r)

x = [abs(a - a_r) for (a, a_r) in zip(cumsum_A[:-1], cumsum_A_r[-2::-1])]
print(min(x))


s = list(input())[:-1]
while True:
  l = len(s)
  h = int(l / 2)
  if l % 2 == 0 and s[:h] == s[h:]:
    break
  s.pop()
print(l)

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

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

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


n=int(input())
a=list(input().split())
ans=[]
i=1
for A in a:
    if i%2: ans.insert(0,A)
    else: ans.append(A)
    i+=1
if i%2: ans.reverse()
print(*ans,sep=' ')


N = 10**6
mod = 10**9 + 7
fact = [1]
for i in range(1, N+1):
    fact.append(fact[-1]*i%mod)

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

if n - m > 1 or m - n > 1:
    ans = 0
elif n - m == 0:
    ans = 2 * fact[n] * fact[m] % mod
else:
    ans = fact[n] * fact[m] % mod

print(ans)

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


import sys

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

def main():
    x,a,b=MI()
    if b<=a:
        print("delicious")
    elif b<=a+x:
        print("safe")
    else:
        print("dangerous")
main()


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

if B <= A:
    print("delicious")
elif B - A <= X:
    print("safe")
else:
    print("dangerous")


N=int(input())
A=[0]*N
for i in range(N):
    A[i]=int(input())

j=0
ans=0
count=[0]*N
while j!=1:
    ans+=1
    j=A[j]-1
    count[ans]=j
    if count.count(j)==2:
        ans=-1
        break

print(ans)

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


def read_input():
    n = int(input())
    alist = [-1]

    for i in range(n):
        alist.append(int(input()))

    return n, alist

def submit():
    n, alist = read_input()

    through = {}
    curr_button = 1
    steps = 0
    while curr_button not in through.keys():
        through[curr_button] = 1
        curr_button = alist[curr_button]
        steps += 1

        if curr_button == 2:
            break

    if curr_button == 2:
        print(steps)
    else:
        print(-1)

if __name__ == '__main__':
    submit()


MOD = 10 ** 9 + 7

def kaijo(n):
    k = 1
    for i in range(1, n + 1):
        k *= i % MOD
    return k

n, m = map(int, input().split())
if n == m:
    print((kaijo(n) ** 2 * 2) % MOD)
elif abs(n - m) > 1:
    print(0)
else:
    if n < m:
        print((kaijo(n) ** 2 * m) % MOD)
    else:
        print((kaijo(m) ** 2 * n) % MOD)

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


import sys
N,M=map(int,input().split())
if abs(N-M)>=2:
    print(0)
    sys.exit()
if N<M:
    N,M=M,N#Nが大きい
table=[1]*(N+1)
mod=10**9+7
for i in range(1,N+1):
    table[i]=(table[i-1]*i)%mod
if N!=M:
    ans=(table[N]*table[M])%mod
    print(ans)
    sys.exit()
print((2*table[N]*table[M])%mod)


import numpy as np

N=int(input())
pos_mat=np.zeros((N,2))
for i in range(N):
    buf=input().split()
    pos_mat[i,0]=int(buf[0])
    pos_mat[i,1]=int(buf[1])

minCost_arr=np.array([float("inf") for _ in range(N)])
used_arr=np.zeros(N, dtype=bool)
minCost_arr[0]=0

totalCost=0
while np.sum(used_arr)<N:

    idx=np.arange(N)[~used_arr]
    u=idx[np.argmin(minCost_arr[idx])]

    totalCost+=minCost_arr[u]
    used_arr[u]=True
    for v in range(N):
        edgeCost=min(abs(pos_mat[u, 0]-pos_mat[v,0]), abs(pos_mat[u, 1]-pos_mat[v,1]))
        minCost_arr[v]=min(minCost_arr[v], edgeCost)
print(int(totalCost))

Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8


H,W,h,w=map(int,input().split())
p=(10**9-1)//(h*w)
m=p*h*w+1
vec=[[p for i in range(W+1)] for j in range(H+1)]
sm=0
for i in range(1,H+1):
  for j in range(1,W+1):
    if i%h==0 and j%w==0:
      vec[i][j]=-m
    sm+=vec[i][j]
if sm<=0:
  print("No")
else:
  print("Yes")
  for i in range(1,H+1):
    for j in range(1,W+1):
      print(vec[i][j],end=" \n"[j==W])

Score : 700 points

Problem Statement

You are given four integers: H, W, h and w (1 ≤ h ≤ H, 1 ≤ w ≤ W).
Determine whether there exists a matrix such that all of the following conditions are held, and construct one such matrix if the answer is positive:

The matrix has H rows and W columns.

Each element of the matrix is an integer between -10^9 and 10^9 (inclusive).

The sum of all the elements of the matrix is positive.

The sum of all the elements within every subrectangle with h rows and w columns in the matrix is negative.

Constraints

1 ≤ h ≤ H ≤ 500

1 ≤ w ≤ W ≤ 500

Input

Input is given from Standard Input in the following format:

H W h w

Output

If there does not exist a matrix that satisfies all of the conditions, print No.

Otherwise, print Yes in the first line, and print a matrix in the subsequent lines in the following format:

a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}

Here, a_{ij} represents the (i,\ j) element of the matrix.

Sample Input 1

3 3 2 2

Sample Output 1

Yes
1 1 1
1 -4 1
1 1 1

The sum of all the elements of this matrix is 4, which is positive.
Also, in this matrix, there are four subrectangles with 2 rows and 2 columns as shown below. For each of them, the sum of all the elements inside is -1, which is negative.

Sample Input 2

2 4 1 2

Sample Output 2

No

Sample Input 3

3 4 2 3

Sample Output 3

Yes
2 -5 8 7
3 -5 -4 -5
2 1 -1 7


s=int(input().replace(" ",""))
print("YES" if s//4==0 else "NO")

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


_ = input()
a = list(map(int, input().strip().split(' ')))
print(max(a)-min(a))

Score : 200 points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.

It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


N = int(input())
A = list(map(int, input().split()))
A = map( lambda x:x//400, A)
A = list(map( lambda x:x if x<8 else 8, A))
cnt8 = A.count(8)
print(cnt8)
A = list(sorted(set(A)))
if 8 in A:
    A.remove(8)
sum = len(A)
if sum == 0 and cnt8 > 0:
    print(1, end=' ')
else:
    print(sum, end=' ')
sum += cnt8
if sum > 8:
    print(8)
else:
    print(sum)

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


import sys
from functools import reduce
import copy
import math
from pprint import pprint
import collections
import bisect

sys.setrecursionlimit(4100000)

def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins

def int_inputs(num_of_input):
    ins = [int(input()) for i in range(num_of_input)]
    return ins

def solve(inputs):
    A = string_to_int(inputs[0])
    rate = [399, 799, 1199, 1599, 1999, 2399, 2799, 3199]

    counter = collections.Counter()
    for a in A:
        hit = -1
        for i, r in enumerate(reversed(rate)):
            if a <= r:
                hit = i
            else:
                break
        counter[hit] += 1

    if -1 in counter.keys():
        n = len(counter.keys()) - 1
        n += counter[-1]
        max_n = len(rate) if n > len(rate) else n
        min_n = len(counter.keys()) - 1
        return '{} {}'.format(min_n, max_n)
    else:
        n = len(counter.keys())
        return '{} {}'.format(n, n)

def string_to_int(string):
    return list(map(int, string.split()))

if __name__ == "__main__":
    input()
    ret = solve(inputs(1))
    print(ret)


A, B = [int(i) for i in input().split()]
if A + B >= 10 :
    print('error')
else :
    print(A + B)

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


s = list(str(input()))
s1 = list(set(s1))

print('yes' if len(s)==len(s1) else 'no')

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |S| denotes the length of S.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


N = int(raw_input())

s = [int(raw_input()) for _ in xrange(N)]
s.sort()

ans = sum(s)
k = 0

for i in range(N):
    if s[i] % 10 != 0:
        k = s[i]
        break

if ans % 10 == 0 and k == 0:
    print 0
elif ans % 10 != 0:
    print ans
else:
    print ans-k

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


a = [1,3,5,7,8,10,12]
b = [4,6,9,11]
ans = 0

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

if x == y:
  print('Yes')
elif x in a and y in a:
  print('Yes')
elif x in b and y in b:
  print('Yes')
else:
  print('No')

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


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

group_1 = set([1, 3, 5, 7, 8, 10, 12])
group_2 = set([4, 6, 9, 11])
group_3 = set([2])

if x in group_1 and y in group_1:
    print("Yes")
elif x in group_2 and y in group_2:
    print("Yes")
else:
    print("No")


h, w = map(int, input().split())

ans = 10 ** 10
for i in range(h):
    x = (i + 1) * w
    mid = (h - i - 1) // 2
    y = mid * w
    z = (h - i - 1 - mid) * w
    ans = min(ans, max(x, y, z) - min(x, y, z))

    mid = w // 2
    y = (h - i - 1) * mid
    z = (h - i - 1) * (w - mid)
    ans = min(ans, max(x, y, z) - min(x, y, z))

for j in range(w):
    x = (j + 1) * h
    mid = (w - j - 1) // 2
    y = mid * h
    z = (w - j - 1 - mid) * h
    ans = min(ans, max(x, y, z) - min(x, y, z))

    mid = h // 2
    y = (w - j - 1) * mid
    z = (w - j - 1) * (h - mid)
    ans = min(ans, max(x, y, z) - min(x, y, z))

print(ans)

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


import sys
from collections import deque, defaultdict
import copy
import bisect
#sys.setrecursionlimit(10 ** 9)
import math
import heapq
from itertools import combinations, permutations

import sys
def input():
	return sys.stdin.readline().strip()

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

a_max = a[:N]
a_min = a[2*N:]

a_max_sum = sum(a_max)
score = [a_max_sum]
heapq.heapify(a_max)
for i in range(N):
	heapq.heappush(a_max, a[N + i])
	a_max_sum += a[N + i]
	a_max_sum -= heapq.heappop(a_max)
	score.append(a_max_sum)
print(score)

a_min_sum = sum(a_min)
score[N] -= a_min_sum
for i in range(len(a_min)):
	a_min[i] *= -1
heapq.heapify(a_min)
for i in range(N):
	heapq.heappush(a_min, -a[2*N - 1 - i])
	a_min_sum += a[2*N - 1 - i]
	a_min_sum += heapq.heappop(a_min)
	score[N - i - 1] -=a_min_sum
print(score)

print(max(score))

Score : 500 points

Problem Statement

Let N be a positive integer.

There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}).
Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements.
Here, the score of a' is defined as follows: (the sum of the elements in the first half of a') - (the sum of the elements in the second half of a').

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

In the test set worth 300 points, N ≤ 1000.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

When a_2 and a_6 are removed, a' will be (3, 4, 1, 5), which has a score of (3 + 4) - (1 + 5) = 1.

Sample Input 2

1
1 2 3

Sample Output 2

-1

For example, when a_1 are removed, a' will be (2, 3), which has a score of 2 - 3 = -1.

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

For example, when a_2, a_3 and a_9 are removed, a' will be (8, 7, 4, 6, 5, 3), which has a score of (8 + 7 + 4) - (6 + 5 + 3) = 5.


# 入力 : 数字3つ
a, b, c = map(int, input().split())

# 整数 C が A 以上 かつ B 以下であるかを判定してください。
if a <= c <= b :
    print("YES")
else :
    print("NO")

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


n, m = map(int, input().split())
l=[0 for i in range(n)]
for i in range(m):
    a,b=map(int, input().split())
    l[a-1]+=1
    l[b-1]+=1
[print(x) for x in l]

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


N,M = map(int, input().split())
E = [[] for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    E[a-1].append((b-1, -c))

#ベルマンフォード法:負閉路の検出とある一点から他のすべての点への最短距離の算出

def BellmanFord(E, N, source):
    #E:E[a]は頂点aを始点とする辺のリストであり、辺の終点bと辺の重みwが(b, w)の形で格納されている
    #N:頂点の数
    #source:始点
    #グラフの初期化
    inf = 10**20
    d = [inf for _ in range(N)]
    d[source] = 0

    #辺の緩和
    for i in range(N):
        for j in range(N):
            e = E[j]
            if len(e) == 0:
                continue
            for edge in e:
                if d[edge[0]] > d[j] + edge[1]:
                    d[edge[0]] = d[j] + edge[1]
                    if i == N-1 and j == N-1: return -1

    return d

dist = BellmanFord(E, N, 0)
if dist == -1:
    print("inf")
else:
    print(-dist[N-1])

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


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

def dibidable_by_two(N):
    ans = 0
    if N ==0:
        return 0
    else:
        while 1:
            if N%2 !=0:
                return ans
            else:
                N /= 2
                ans += 1

if A == B == C:
    print(-1)
else:
    ans = 2**100000
    for M in [A,B,C]:
        if M!=0:
            ans=min(ans,dibidable_by_two(M))

    if ans == 2**100000:
        print(0)
    else:
        print(ans)

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


import numpy as np
import sys

input = sys.stdin.readline

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

ans = 0

if A == B and  B == C:
    ans = -1
else:
    while A%2 == 0 and B%2 == 0 and C%2 == 0:
        next_a = C/2 + B/2
        next_b = A/2 + C/2
        next_c = A/2 + B/2
        A = next_a
        B = next_b
        C = next_c
        ans += 1

print(ans)


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

while True:
    if a%2 == 0 and b%2 == 0 and c%2 == 0:
        pass
    else:
        print(ans)
        exit()

    last_a = a
    last_b = b
    last_c = c
    a,b,c = (b+c)//2, (a+c)//2, (a+b)//2

    ans += 1

    if last_a == a and last_b == b and last_c == c:
        print(-1)
        exit()


# -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline

INF = 2**62-1

def read_int():
    return int(buff_readline())

def read_int_n():
    return list(map(int, buff_readline().split()))

def read_float():
    return float(buff_readline())

def read_float_n():
    return list(map(float, buff_readline().split()))

def read_str():
    return readline().strip()

def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)

def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap

@mt
def slv(H, W, K, A):
    for i in range(H):
        for j in range(W):
            if A[i][j] == 'S':
                s = (i, j)
    from collections import deque

    q = deque([s])
    d = [[None] * W for _ in range(H)]
    d[s[0]][s[1]] = 0

    ans = INF
    while q:
        x, y = q.popleft()
        ans = min(ans, min(abs(x), abs(x-H+1), abs(y), abs(y-W+1)))
        c = d[x][y]
        if c + 1 > K:
            continue
        for vx, vy in [(x-1, y), (x, y-1), (x, y+1), (x+1, y)]:
            if not (0 <= vx < H and 0 <= vy < W):
                continue
            if A[vx][vy] == '#':
                continue
            if d[vx][vy] is not None:
                continue
            q.append((vx, vy))
            d[vx][vy] = c + 1

    return 1 + -(-ans // K)

def main():
    H, W, K = read_int_n()
    A = [read_str() for _ in range(H)]
    print(slv(H, W, K, A))

if __name__ == '__main__':
    main()

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


a, b, c = input().split(" ")

if a[-1] == b[0] and b[-1] == c[0]:
    print("YES")
else:
    print("NO")

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


a, b, c = map(int, input().split())
ans = "NO"
for num in range(1, 5051):
    if num % a == 0:
        if num % b == c:
            ans = "YES"
            break

print(ans)

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


N, T = map(int, input().split())
t = [int(i) for i in input().split()]
ans = T
wait = 0
start = 0
for i in range(1, N):
    if (t[i] - t[i - 1] >= T):
        ans += wait + T
        start = t[i]
        wait = 0
    else:
      wait = t[i] - start
      if (wait > T):
            ans, wait = ans + T, wait - T
print(ans + wait)

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


N, T = list(map(int, input().split()))
t = list(map(int, input().split()))
ans = 0
end = 0
for tt in t:
	diff = 0 if end <= tt else end - tt
	ans += T - diff
	end = tt + T
print(ans)


import sys
from collections import defaultdict
import numpy as np

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7

def input():
    return sys.stdin.readline().strip()

def main():
    N, W = map(int, input().split())
    d = defaultdict(list)
    w, v = map(int, input().split())
    w1 = w
    d[w].append(v)
    for _ in range(1, N):
        w, v = map(int, input().split())
        d[w].append(v)

    cumsum = dict()
    L = dict()
    for i in range(4):
        w = w1 + i
        d[w].sort(reverse=True)
        c = np.cumsum(d[w])
        cumsum[w] = c
        L[i] = len(d[w])

    ans = 0
    for i in range(L[0] + 1):
        if i != 0:
            v1 = cumsum[w1][i - 1]
        else:
            v1 = 0
        for j in range(L[1] + 1):
            if j != 0:
                v2 = v1 + cumsum[w1 + 1][j - 1]
            else:
                v2 = v1
            for k in range(L[2] + 1):
                if k != 0:
                    v3 = v2 + cumsum[w1 + 2][k - 1]
                else:
                    v3 = v2
                for l in range(L[3] + 1):
                    w = w1 * i + (w1 + 1) * j + (w1 + 2) * k + (w1 + 3) * l
                    if w > W:
                        continue

                    if l != 0:
                        v4 = v3 + cumsum[w1 + 3][l - 1]
                    else:
                        v4 = v3

                    if v4 > ans:
                        ans = v4

    print(ans)

if __name__ == "__main__":
    main()

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


a = int(input())
b = int(input())

if a > b:
    print("GREATER")
elif b > a:
    print("LESS")
else:
    print("EQUAL")

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = inn()
a = inl()
ne = sum(a[::2])
no = sum(a[1::2])
p0 = (ne>no)
cnt = 0
acc = 0
#ddprint("ne {} no {} p0 {} a {}".format(ne,no,p0,a))
for i in range(n):
    if (p0 if i%2==0 else not p0):
        x = max(0, 1-a[i]-acc)
        cnt += x
        acc += a[i]+x
    else:
        x = max(0, a[i]+acc+1)
        cnt += x
        acc += a[i]-x
    #ddprint("cnt {} acc {}".format(cnt,acc))
print(cnt)

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


def main()->None:
    # 回答見た
    n = int(input())
    a = list(map(int, input().split()))
    range_N = range(n)
    acounter = 0
    bcounter = 0
    num = 0
    for i in range_N:
        num += a[i]
        if i % 2 == 0:
            if num <= 0:
                acounter += abs(num) + 1
                num = 1

        else:
            if num >= 0:
                acounter += num + 1
                num = -1

    num = 0
    for i in range_N:
        num += a[i]
        if i % 2 != 0:
            if num <= 0:
                bcounter += abs(num) + 1
                num = 1

        else:
            if num >= 0:
                bcounter += num + 1
                num = -1

    print(min(acounter, bcounter))

if __name__ == "__main__":
    main()


import copy

n = int(input())
a = list(map(int,input().split()))
b = [0]

for i in range(len(a)):
    b.append(b[i] + a[i])

del b[0]

c = copy.copy(b)

first_minus = 0
first_plus = 0

for i in range(len(b)):
    if(i%2 == 0):
        if (b[i] >= 0):
            diff =  abs(b[i]) + 1
            first_minus = first_minus +  diff
            b = list(map(lambda x: x - diff, b))

        if (c[i] <= 0):
            diff =  abs(c[i]) + 1
            first_plus = first_plus +  diff
            c = list(map(lambda x: x + diff, c))
    else:
        if (b[i] <= 0):
            diff =  abs(b[i]) + 1
            first_minus = first_minus +  diff
            b = list(map(lambda x: x + diff, b))

        if (c[i] >= 0):
            diff =  abs(c[i]) + 1
            first_plus = first_plus +  diff
            c = list(map(lambda x: x - diff, c))

print(min(first_minus,first_plus))


from numpy import cumsum,copy
n = int(input())
a = cumsum([int(i) for i in input().split()])
b = copy(a)
ans1 = ans2 = 0
sign = 1
for i in range(n):
    if a[i] * sign <= 0:
        k = abs(a[i] - sign)
        a += sign*k
        ans1 += k
    sign *= -1
sign = -1
for i in range(n):
    if b[i] * sign <= 0:
        k = abs(b[i] - sign)
        b += sign*k
        ans2 += k
    sign *= -1
print(min(ans1, ans2))


xy=[int(i) for i in input().split()]
if sum(xy)%2==0:
	print("Alice")
else:
	print("Brown")

Score : 500 points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of X and Y stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take 2i stones from one of the piles. Then, throw away i of them, and put the remaining i in the other pile. Here, the integer i (1≤i) can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given X and Y, determine the winner of the game, assuming that both players play optimally.

Constraints

0 ≤ X, Y ≤ 10^{18}

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice


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

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

ants = []
for i in range(N):
    x, w = map(int, input().split())
    ants.append((x, w))

# After T
ants2 = []
for ant in ants:
    if ant[1] == 1:
        ants2.append((ant[0] + T) % L)
    else:
        ants2.append((ant[0] - T) % L)

# Number of collision for Ants[0]
cl = 0
for i in range(1, N):
    if ants[i][1] == ants[0][1]:
        continue  # same direction
    else:
        if ants[0][1] == 1:
            fc = (ants[i][0] - ants[0][0]) / 2
            cl += int(2 * (T - fc) / L) + 1
        else:
            fc = ((L - ants[i][0]) + ants[0][0]) / 2
            cl -= int(2 * (T - fc) / L) + 1

ant1 = ants2[0]
ants2.sort()
idx = ants2.index(ant1) - cl

for i in range(N):
    print(ants2[(i + idx) % N])

Score : 700 points

Problem Statement

There is a circle with a circumference of L.
Each point on the circumference has a coordinate value, which represents the arc length from a certain reference point clockwise to the point.
On this circumference, there are N ants.
These ants are numbered 1 through N in order of increasing coordinate, and ant i is at coordinate X_i.

The N ants have just started walking.
For each ant i, you are given the initial direction W_i. Ant i is initially walking clockwise if W_i is 1; counterclockwise if W_i is 2.
Every ant walks at a constant speed of 1 per second.
Sometimes, two ants bump into each other.
Each of these two ants will then turn around and start walking in the opposite direction.

For each ant, find its position after T seconds.

Constraints

All input values are integers.

1 \leq N \leq 10^5

1 \leq L \leq 10^9

1 \leq T \leq 10^9

0 \leq X_1 < X_2 < ... < X_N \leq L - 1

1 \leq W_i \leq 2

Input

The input is given from Standard Input in the following format:

N L T
X_1 W_1
X_2 W_2
:
X_N W_N

Output

Print N lines.
The i-th line should contain the coordinate of ant i after T seconds. Here, each coordinate must be between 0 and L-1, inclusive.

Sample Input 1

3 8 3
0 1
3 2
6 1

Sample Output 1

1
3
0

1.5 seconds after the ants start walking, ant 1 and 2 bump into each other at coordinate 1.5.
1 second after that, ant 1 and 3 bump into each other at coordinate 0.5.
0.5 seconds after that, that is, 3 seconds after the ants start walking, ants 1, 2 and 3 are at coordinates 1, 3 and 0, respectively.

Sample Input 2

4 20 9
7 2
9 1
12 1
18 1

Sample Output 2

7
18
18
1


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

ba = b - a
cb = c - b

if ba == cb:
    print("Yes")
else:
    print("No")

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


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

if(b-a) ==(c-b):
    print('YES')
else:
    print('NO')


def solve():
  n= int(input())
  a = list(int(i) for i in input().split())
  a.sort()
  #前から一*n人削除
  a = a[n::]
  #後から二人分削除
  ans = 0
  for i in range(2*n):
   if i%2 == 0: ans += a[i]
  return ans

if __name__ == '__main__':
  print(solve())

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


tmp = input().split()
a, b = int(tmp[0]), int(tmp[1])

s = a + b

if s < 24:
    print(s)
else:
    print(s-24)


n, m = map(int, input().split())
s = [list(map(int, input().split())) for _ in range(n)]
p = [list(map(int, input().split())) for _ in range(m)]
for i in range(n):
    mindis = 10 ** 9
    for j in range(m):
        dis = abs(s[i][0] - p[j][0]) + abs(s[i][1] - p[j][1])
        if mindis > dis:
            p = j+1
            mindis = dis
    print(p)

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


S = input().split()
if S[0] == S[1]: print("H")
else: print("D")

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

The input is given from Standard Input in the following format:

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


a,b=map(str,input().split())
if a=='H' and b=='H':
    print('H')
elif a=='D' and b=='D':
    print('H')
else:
    print('D')


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

if a+w < b:
    print(b-(a+w))
elif b+w < a:
    print(a-(b+w))
else:
    print(0)

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

The input is given from Standard Input in the following format:

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


#43 C - Go Home
X = int(input())

sum_i = 0
for i in range(1,10**5):
    sum_i += i
    if sum_i >= X:
        ans = i
        break
print(ans)

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

The input is given from Standard Input in the following format:

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


import math

X = int(input())

x = max(0, int(math.sqrt(X)) - 10)

while True:
    xx = x * (x + 1) // 2
    if X <= xx:
        print(x)
        exit()
    else:
        x += 1


x = int(input())

distance = 0
count = 0

i = 1
while distance < x:
    distance += i
    count += 1
    i += 1

print(count)


N, K = map(int, input().split())
A = list(map(int, input().split()))
A = [a for a in A if a <K]
N = len(A)
dp2 = [1] + [0]*K
dpm = [[0]*(K+1) for _ in range(N+1)]
dpm[0][0] = 1
for i, a in enumerate(A):
    for j in range(K, -1, -1):
        dpm[i+1][j] = dpm[i][max(0, j-a)] + dpm[i][j]
#print(dpm)

r = 0
for i, a in enumerate(A[::-1]):
    f = True
    for j in range(K, -1, -1):
        # 後ろiこの合計がjのもの
        if f and dp2[j] > 0:
            # K-j > x >= K-j-a
            if dpm[N-i-1][max(0, K-j-a)] > dpm[N-i-1][K-j]:
                f = False
        if j-a>=0:
            dp2[j] = dp2[j] + dp2[j-a]
    if f:
        r += 1
#    for j in range(K-1, 0, -1):
#        print("aa", i, N-i-1)
print(r)


Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


N = int(input())

p = 1
for i in range(1, N+1):
    p *= i
    p %= (10**9 + 7)

print(p)

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


N, M = map(int, input().split(' '))
def sunuke_f3(n, m) :
    if n >= m :
        return(m//2)
    else :
        if 2*n < m :
            return(n + (m-2*n)//4)
        else :
            return(m//2)
print(sunuke_f3(N, M))

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

The input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


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

res = 'W'
if s[0] == 'o':
    res += 'S'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'W' and res[-2] == 'W':
        print(res[:-1])
        exit()
res = 'W'
if s[0] == 'o':
    res += 'W'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'W' and res[-2] == 'S':
        print(res[:-1])
        exit()
res = 'W'
if s[0] == 'x':
    res += 'S'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'W' and res[-2] == 'S':
        print(res[:-1])
        exit()
res = 'W'
if s[0] == 'x':
    res += 'W'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'W' and res[-2] == 'W':
        print(res[:-1])
        exit()

res = 'S'
if s[0] == 'o':
    res += 'S'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'S' and res[-2] == 'S':
        print(res[:-1])
        exit()
res = 'S'
if s[0] == 'o':
    res += 'W'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'S' and res[-2] == 'W':
        print(res[:-1])
        exit()
res = 'S'
if s[0] == 'x':
    res += 'S'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'S' and res[-2] == 'W':
        print(res[:-1])
        exit()
res = 'S'
if s[0] == 'x':
    res += 'W'
    for i in range(2,n+1):
        if s[i-1] == 'o':
            if res[i-1] == 'S':
                t = res[i-2]
            else:
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
        else:
            if res[i - 1] == 'S':
                if res[i-2] == 'S':
                    t = 'W'
                else:
                    t = 'S'
            else:
                t = res[i - 2]
        res += t
    if res[-1] == 'S' and res[-2] == 'S':
        print(res[:-1])
        exit()

print(-1)

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

The input is given from Standard Input in the following format:

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


N = int(input())
s= input()

ans = list("S"*(N+1))
for i in range(0, N):
    # 羊の処理
    if ans[i]=="S":
        # o or xで分岐
        if s[i]=="o":
            ans[i+1]=ans[i-1]
        else:
              # 羊x
             ans[i+1]= "S" if ans[i-1]=="W" else "W"
    else:
        if s[i]=="o":
            # 狼o
            ans[i+1]= "S" if ans[i-1]=="W" else "W"
        else:
              # 狼x
             ans[i+1]=ans[i-1]

if ans[0]==ans[N]:
    print("".join(ans[:-1]))
else:
    print(-1)


N,M = map(int,input().split())
if M - 2*N > 0:
    rm = M - 2*N
    print(N + rm // 4)
else:
    print(M // 2)


from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,copy,time
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

N = inp()

class BinaryIndexedTree():
    def __init__(self,N):
        self.N = N
        self.bit = [0]*(self.N+1)

    def add(self,a,w):
        a += 1
        x = a
        while x <= self.N:
            self.bit[x] += w
            x += x & -x

    def sum(self,a):
        a += 1
        tmp = 0
        x = a
        while x > 0:
            tmp += self.bit[x]
            x -= x & -x
        return tmp

BIT = BinaryIndexedTree(N)
aa = inpl()

i2a = sorted(list(set(aa)))
a2i = defaultdict(int)
for i,a in enumerate(i2a):
    a2i[a] = i

koho = [0]*N
ba = 0
for i,a in enumerate(aa):
    if ba < a:
        koho[i] = a- ba
        ba = a

ans = [0]*N
for ri,a in enumerate(reversed(aa)):
    i = N-1-ri
    BIT.add(a2i[a], 1)

    if koho[i]:
        ans[i] =  (BIT.sum(N-1) - BIT.sum(a2i[a]-1)) * koho[i]

ans[0] += sum(aa) - sum(ans)

print('\n'.join(map(str,ans)))

Score : 700 points

Problem Statement

Snuke loves constructing integer sequences.

There are N piles of stones, numbered 1 through N.
The pile numbered i consists of a_i stones.

Snuke will construct an integer sequence s of length Σa_i, as follows:

Among the piles with the largest number of stones remaining, let x be the index of the pile with the smallest index. Append x to the end of s.

Select a pile with one or more stones remaining, and remove a stone from that pile.

If there is a pile with one or more stones remaining, go back to step 1. Otherwise, terminate the process.

We are interested in the lexicographically smallest sequence that can be constructed. For each of the integers 1,2,3,...,N, how many times does it occur in the lexicographically smallest sequence?

Constraints

1 ≤ N ≤ 10^{5}

1 ≤ a_i ≤ 10^{9}

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print N lines. The i-th line should contain the number of the occurrences of the integer i in the lexicographically smallest sequence that can be constructed.

Sample Input 1

2
1 2

Sample Output 1

2
1

The lexicographically smallest sequence is constructed as follows:

Since the pile with the largest number of stones remaining is pile 2, append 2 to the end of s. Then, remove a stone from pile 2.

Since the piles with the largest number of stones remaining are pile 1 and 2, append 1 to the end of s (we take the smallest index). Then, remove a stone from pile 2.

Since the pile with the largest number of stones remaining is pile 1, append 1 to the end of s. Then, remove a stone from pile 1.

The resulting sequence is (2,1,1). In this sequence, 1 occurs twice, and 2 occurs once.

Sample Input 2

10
1 2 1 3 2 4 2 5 8 1

Sample Output 2

10
7
0
4
0
3
0
2
3
0


from sys import stdin
import itertools
N,M = [int(x) for x in stdin.readline().rstrip().split()]

edges = []
for m in range(M):
    a,b = [int(x) for x in stdin.readline().rstrip().split()]
    edges.append((a,b))
    edges.append((b,a))

node = list(range(1,N+1))

ans = 0
for i in itertools.permutations(node):
    f = True
    for j in range(len(i)-1):
        if (not (i[j],i[j+1]) in edges):
            f = False
    if f and i[0] == 1:
        ans += 1
print(ans)

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


import math
from collections import defaultdict
import itertools
def input_as_int():
    return tuple(map(int,input().split()))

N,M  = input_as_int()

path = defaultdict(lambda  :defaultdict(lambda :False))
for i in range(M):
    a,b = input_as_int()
    path[a][b] = path[b][a] = True

ans = 0
roots = itertools.permutations(list(range(2,N+1)))
for root in roots:
    fr = 1
    flag = True
    for to in root:
        if path[fr][to]:
            fr = to
        else:
            flag = False
            break
    if flag:
        ans += 1
print(ans)


def dfs(v,N,visited):
    allvis=True
    for i in range(N):
        if visited[i]==False:
            allvis=False
    if allvis:
        return 1
    ret=0

    for i in range(N):
        if graph[v][i]==False:
            continue
        if visited[i]:
            continue
        visited[i]=True
        ret+=dfs(i,N,visited)
        visited[i]=False
    return ret

N,M = map(int, input().strip().split())
graph = [[False] * N for i in range(N)]
for i in range(M):
    a,b=map(int,input().strip().split())
    graph[a-1][b-1]=True
    graph[b-1][a-1]=True

visited=[False]*N
visited[0]=True

print(dfs(0,N,visited))


mod=1777777777
n,ma,mb=map(int,input().split())
d=[[mod for j in range(100)] for i in range(100)]
for i in range(n):
    a,b,c=map(int,input().split())
    x=a
    y=b
    d[x][y]=min(d[x][y],c)
    for j in range(100-a):
        for k in range(100-b):
            if d[j][k]!=mod:
                d[j+a][k+b]=min(d[j+a][k+b],d[j][k]+c)
ans=mod
for i in range(100):
    if i%ma==0 and mb*i//ma<100:
        ans=min(ans,d[i][mb*i//ma])

print([ans,-1][ans==mod])

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

The input is given from Standard Input in the following format:

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

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

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.


import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

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

cnt = 0
for i in range(n):
    if a[i] %2 == 1: cnt+=1

if cnt%2==1:
    print('NO')
else:
    print('YES')

Score : 300 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, A_i+A_j.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

2 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase 1 and 3 from the blackboard, then write 4. Now, there are two integers on the blackboard: 2 and 4.

Erase 2 and 4 from the blackboard, then write 6. Now, there is only one integer on the blackboard: 6.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO


#!/usr/bin/env python3
X = int(input())
if X < 1200:
    print('ABC')
else:
    print('ARC')

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


x = int(input())
count = 0

count = x//11*2
if x-count*11/2 <= 6:
    count += 1
else:
    count += 2
print(count)

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


n = int(input())

times = 0

times += n // 11
rest = n % 11

if rest == 0:
    next
elif n < 7:
    times += 1
else:
    times += 2

print(times)