i=int(input())
A, T = input().strip().split(' ')
A, T = [int(A), int(T)]
array = list(map(int, input().strip().split(' ')))
ans=[0]＊i
ans[i]=abs(array[i]-(A-T)/0.006)
kai=ans[i]
for j in range(0,i,1):
    ans[j]=abs(array[j]-(A-T)/0.006)
    if ans[j]＜kai
        kai=ans[j]
        ko=j
print(ko)

Score: 200 points

Problem Statement

A country decides to build a palace.

In this country, the average temperature of a point at an elevation of x meters is T-x \times 0.006 degrees Celsius.

There are N places proposed for the place. The elevation of Place i is H_i meters.

Among them, Princess Joisino orders you to select the place whose average temperature is the closest to A degrees Celsius, and build the palace there.

Print the index of the place where the palace should be built.

It is guaranteed that the solution is unique.

Constraints

1 \leq N \leq 1000

0 \leq T \leq 50

-60 \leq A \leq T

0 \leq H_i \leq 10^5

All values in input are integers.

The solution is unique.

Input

Input is given from Standard Input in the following format:

N
T A
H_1 H_2 ... H_N

Output

Print the index of the place where the palace should be built.

Sample Input 1

2
12 5
1000 2000

Sample Output 1

1

The average temperature of Place 1 is 12-1000 \times 0.006=6 degrees Celsius.

The average temperature of Place 2 is 12-2000 \times 0.006=0 degrees Celsius.

Thus, the palace should be built at Place 1.

Sample Input 2

3
21 -11
81234 94124 52141

Sample Output 2

3


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

Score : 400 points

Problem Statement

You are given N integers; the i-th of them is A_i.
Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like.

Constraints

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum possible sum of the absolute differences between the adjacent elements after arranging the given integers in a row in any order you like.

Sample Input 1

5
6
8
1
2
3

Sample Output 1

21

When the integers are arranged as 3,8,1,6,2, the sum of the absolute differences between the adjacent elements is |3 - 8| + |8 - 1| + |1 - 6| + |6 - 2| = 21. This is the maximum possible sum.

Sample Input 2

6
3
1
4
1
5
9

Sample Output 2

25

Sample Input 3

3
5
5
1

Sample Output 3

8

Submitted source-code file size, in bytes.

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

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


s=input()
if len(s)==2:
    print(s)
else:
    print(s[2]+s[1]+s[0])

Score : 100 points

Problem Statement

You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it.

Constraints

The length of S is 2 or 3.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If the length of S is 2, print S as is; if the length is 3, print S after reversing it.

Sample Input 1

abc

Sample Output 1

cba

As the length of S is 3, we print it after reversing it.

Sample Input 2

ac

Sample Output 2

ac

As the length of S is 2, we print it as is.


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

b = a[0]
c = a[1]

for i in range(a[2]):
    if i % 2 == 0:
        b //= 2
        c += b
    else:
        c //= 2
        b += c

print(b,c)

Score : 200 points

Problem Statement

In the beginning, Takahashi has A cookies, and Aoki has B cookies.
They will perform the following operation alternately, starting from Takahashi:

If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other person.

Find the numbers of cookies Takahashi and Aoki respectively have after performing K operations in total.

Constraints

1 \leq A,B \leq 10^9

1 \leq K \leq 100

A,B and K are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the number of cookies Takahashi has, and the number of cookies Aoki has, in this order, after performing K operations in total.

Sample Input 1

5 4 2

Sample Output 1

5 3

The process will go as follows:

In the beginning, Takahashi and Aoki have 5 and 4 cookies, respectively.

Takahashi eats one cookie and gives two cookies to Aoki. They now have 2 and 6 cookies, respectively.

Aoki gives three cookies to Takahashi. They now have 5 and 3 cookies, respectively.

Sample Input 2

3 3 3

Sample Output 2

1 3

Sample Input 3

314159265 358979323 84

Sample Output 3

448759046 224379523


# https://atcoder.jp/contests/tenka1-2018-beginner/tasks/tenka1_2018_c
from collections import deque
n = int(input())
nums = []
for _ in range(n):
    nums.append(int(input()))
nums.sort()
ans = 0
l = 0
r = n - 1
q = deque()
while l <= r:
    left = nums[l]
    right = nums[r]
    if not q:
        ans += abs(right - left)
        q.append(left)
        q.append(right)
        l += 1
        r -= 1
    else:
        s = max(abs(q[-1] - right), abs(q[0] - right))
        t = max(abs(q[-1] - left), abs(q[0] - left))
        if s >= t:
            if abs(q[-1] - right) > abs(q[0] - right):
                ans += abs(q[-1] - right)
                q.append(right)
            else:
                ans += abs(q[0] - right)
                q.appendleft(right)
            r -= 1
        else:
            if abs(q[-1] - left) > abs(q[0] - left):
                ans += abs(q[-1] - left)
                q.append(left)
            else:
                ans += abs(q[0] - left)
                q.appendleft(left)
            l += 1
print(ans)


import sys
input = sys.stdin.readline

def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))

def main():
    mod=10**9+7
    N=I()
    if N%2==0:
        print("No")
    else:
        print("Yes")
        print(2+N//2)
        L1=list(range(1,2+N//2))
        L2=list(range(1+N//2,N+1))
        print(' '.join(map(str, [len(L1)]+L1)))
        print(' '.join(map(str, [len(L2)]+L2)))
        for i in range(N//2):
            print(2,i+1,i+2+N//2)

main()

Score : 500 points

Problem Statement

You are given an integer N. Determine if there exists a tuple of subsets of \{1,2,...N\}, (S_1,S_2,...,S_k), that satisfies the following conditions:

Each of the integers 1,2,...,N is contained in exactly two of the sets S_1,S_2,...,S_k.

Any two of the sets S_1,S_2,...,S_k have exactly one element in common.

If such a tuple exists, construct one such tuple.

Constraints

1 \leq N \leq 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If a tuple of subsets of \{1,2,...N\} that satisfies the conditions does not exist, print No.
If such a tuple exists, print Yes first, then print such subsets in the following format:

k
|S_1| S_{1,1} S_{1,2} ... S_{1,|S_1|}
:
|S_k| S_{k,1} S_{k,2} ... S_{k,|S_k|}

where S_i={S_{i,1},S_{i,2},...,S_{i,|S_i|}}.

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

Sample Input 1

3

Sample Output 1

Yes
3
2 1 2
2 3 1
2 2 3

It can be seen that (S_1,S_2,S_3)=(\{1,2\},\{3,1\},\{2,3\}) satisfies the conditions.

Sample Input 2

4

Sample Output 2

No


n=int(input())

if n == 1:
    print("Hello World")
elif n == 2:
    ab=[input() for i in range(n)]
    print(int(ab[0])+int(ab[1]))

Score: 100 points

Problem Statement

In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers A, B and prints A+B.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age N (1 or 2) as input, then prints Hello World if N=1, and additionally receives integers A, B and prints A+B if N=2.

Write this program for him.

Constraints

N is 1 or 2.

A is an integer between 1 and 9 (inclusive).

B is an integer between 1 and 9 (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
A
B

Output

If N=1, print Hello World; if N=2, print A+B.

Sample Input 1

1

Sample Output 1

Hello World

As N=1, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As N=2, Takahashi is two years old. Thus, we should print A+B, which is 8 since A=3 and B=5.


N,T=list(map(int,input().split()))
minCos = 10000
ans = 0
for i in range(N):
  c,t=list(map(int,input().split()))
  if t <= T:
    if min(minCos,c) == c:
      ans = i+1
      minCos = c
if ans == 0:
  print("TLE")
else:
  print(ans)

Score : 200 points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found N routes to his home.

If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.

Find the smallest cost of a route that takes not longer than time T.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq T \leq 1000

1 \leq c_i \leq 1000

1 \leq t_i \leq 1000

The pairs (c_i, t_i) are distinct.

Input

Input is given from Standard Input in the following format:

N T
c_1 t_1
c_2 t_2
:
c_N t_N

Output

Print the smallest cost of a route that takes not longer than time T.

If there is no route that takes not longer than time T, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost 7.

The second route takes longer than time T = 70.

The third route gets him home at cost 4.

Thus, the cost 4 of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time T = 3.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5


N,T = map(int,input().split())
c = []
t = []
for i in range(N):
  a,b = map(int,input(),split())
  c.append(a)
  t.append(b)
result = []
for j in range(N):
  if T >= t[j]:
    result.append(c[j])
  else:
    None
print(min(result))


N,T=map(int,input().split())
ans=10**10
for i in range(N):
    c,t=map(int,input().split())
    if c<ans and t<=T: ans=c
print("TLE" if ans==10**10 else ans)


n, m = map(int, input().split())
d = []
for i in range(1, m + 1):
  if i * i > m:
    break
  if m % i == 0:
    d.append(i)
    d.append(m // i)
ans = 1
for i in d:
  if i * n <= m:
    ans = max(ans, i)
print(ans)

Score : 400 points

Problem Statement

You are given integers N and M.

Consider a sequence a of length N consisting of positive integers such that a_1 + a_2 + ... + a_N = M. Find the maximum possible value of the greatest common divisor of a_1, a_2, ..., a_N.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

N \leq M \leq 10^9

Input

Input is given from Standard Input in the following format:

N M

Output

Print the maximum possible value of the greatest common divisor of a sequence a_1, a_2, ..., a_N that satisfies the condition.

Sample Input 1

3 14

Sample Output 1

2

Consider the sequence (a_1, a_2, a_3) = (2, 4, 8). Their greatest common divisor is 2, and this is the maximum value.

Sample Input 2

10 123

Sample Output 2

3

Sample Input 3

100000 1000000000

Sample Output 3

10000


N=int(input())
ans=N
while(True):
  if len(set(str(ans).split()))==1:
    print(ans)
    break
  else:
    ans+=1

Score : 200 points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC N (the N-th ABC ever held).
Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

100 \leq N \leq 999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If the earliest ABC where Kurohashi can make his debut is ABC n, print n.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC 111, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC 112, which means Kurohashi can no longer participate in ABC 111.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC 222.

Sample Input 3

750

Sample Output 3

777


n = input()
ans = []
for i in range(len(n)):
    s = 100*int(n[i])+10*int(n[i])+int(n[i])
    ans.append(s)
print(max(ans))


# 初期入力
from collections import Counter
import sys
input = sys.stdin.readline  #文字列では使わない
n = int(input())
v = list(map(int, input().split()))
vo1 =v[1::2]
ve2 =v[0::2]
co1_k,co1_v = zip(*Counter(vo1).most_common())
ce2_k,ce2_v = zip(*Counter(ve2).most_common())
"""
co1_l =list(co1.values())
ce2_l =list(ce2.values())
co1_l.sort(reverse=True)
ce2_l.sort(reverse=True)
"""
ans =0

if vo1 ==ve2:
    ans =len(vo1)
elif len(co1_v) ==len(ce2_v) ==1:
    ans =0
elif co1_k[0] ==ce2_k[0]:
    if len(co1_v) ==1:
        ans =sum(ce2_v[1:])
    elif len(ce2_v) ==1:
        ans =sum(co1_v[1:])
    elif len(co1_v) ==len(ce2_v) ==2:
        ans1 =co1_v[1] +ce2_v[0]
        ans2 =co1_v[0] +ce2_v[1]
        ans =min(ans1,ans2)
    elif len(co1_v) ==2:
        ans1 =co1_v[1] +ce2_v[0] +sum(ce2_v[2:])
        ans2 =co1_v[0] +sum(ce2_v[1:])
        ans =min(ans1,ans2)
    elif len(ce2_v) ==2:
        ans1 =ce2_v[1] +co1_v[0] +sum(co1_v[2:])
        ans2 =ce2_v[0] +sum(co1_v[1:])
        ans =min(ans1,ans2)
    else:
        ans1 =sum(co1_v[1:]) +ce2_v[0] +sum(ce2_v[2:] )
        ans1 =sum(ce2_v[1:]) +co1_v[0] +sum(co1_v[2:] )
        ans =min(ans1,ans2)
else:
    if len(co1_v) ==1:
        ans =sum(ce2_v[1:])
    elif len(ce2_v) ==1:
        ans =sum(co1_v[1:])
    else:
        ans =sum(co1_v[1:]) +sum(ce2_v[1:])

print(ans)

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.


import collections
def main():
    n=int(input())
    v=list(map(int,input().split()))
    ve=[]
    vo=[]
    for i in range(n//2):
        ve.append(v[2*i])
        vo.append(v[2*i+1])
    ce=collections.Counter(ve)
    co=collections.Counter(vo)
    eMax=ce.most_common()[0][1]
    oMax=co.most_common()[0][1]
    if ce.most_common()[0][0]==co.most_common()[0][0]:
        if ce.most_common()[0][1]<=co.most_common()[0][1]:
            if len(ce)==1:
                eMax=0
            else:
                eMax=ce.most_common()[1][1]
        else:
            if len(co)==1:
                oMax=0
            else:
                oMax=co.most_common()[1][1]
    print(n-eMax-oMax)
if __name__=="__main__":
    main()


from collections import Counter
N = int(input())
*V, = map(int, input().split())
if set(V) == 1:
    print(N//2)
    exit()
even, odd = Counter(V[::2]).most_common(), Counter(V[1::2]).most_common()
print(N - even[0][1] - odd[0][1])


import collections

n = int(input())
v = list(map(int, input().split()))
odd = []
even = []
for i in range(int(n/2)):
    even.append(v[2*i])
    odd.append(v[2*i + 1])
evencount = collections.Counter(even)
oddcount = collections.Counter(odd)

if evencount.most_common()[0][0] != oddcount.most_common()[0][0]:
    ans = n - evencount.most_common()[0][1] - oddcount.most_common()[0][1]
else:
    if evencount.most_common()[0][1] > oddcount.most_common()[0][1]:
        if len(oddcount)!=1:
            ans = n - evencount.most_common()[0][1] - oddcount.most_common()[1][1]
        else:
            ans = n - evencount.most_common()[0][1]
    else:
        if len(evencount)!=1:
            ans = n - evencount.most_common()[1][1] - oddcount.most_common()[0][1]
        else:
            ans = n - oddcount.most_common()[0][1]

print(ans)


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

l=[v[i] for i in range(n) if i%2==0]
r=[v[i] for i in range(n) if i%2]

l.sort()
r.sort()

count=1
countl1=0
countl2=0

for i in range(1,len(l)):
    if l[i]==l[i-1]: count+=1
    else:
        if count>=countl1:
            countl1,countl2=count,countl1
            charl=l[i-1]
        elif count>countl2:
            countl2=count
        count=1

if count>=countl1:
    countl1,countl2=count,countl1
    charl=l[-1]
elif count>countl2:
    countl2=count

count=1
countr1=0
countr2=0

for i in range(1,len(r)):
    if r[i]==r[i-1]: count+=1
    else:
        if count>=countr1:
            countr1,countr2=count,countr1
            charr=r[i-1]
        elif count>countr2:
            countr2=count
        count=1

if count>=countr1:
    countr1,countr2=count,countr1
    charr=r[-1]
elif count>countr2:
    countr2=count

if charl==charr:
    print(n-max(countl1+countr2,countl2+countr1))
else: print(n-countl1-countr1)


import collections
s = input()
t = input()
s_cnt = collections.Counter(s)
t_cnt = collections.Counter(t)
a = s_cnt.most_common()
b = t_cnt.most_common()
ans = True
for i in range(len(a)):
    if a[i][1] != b[i][1]:
        ans = False
        break

print('Yes' if ans else 'No')

Score : 300 points

Problem Statement

You are given strings S and T consisting of lowercase English letters.

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

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

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


from itertools import*;i=lambda:sorted([len(list(v))for k,v in groupby(input()]);print('YNeos'[i()!=i()::2])


n,m=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
s=0
while s<n:
  if m>=a[s]:
    m-=a[s]
    s+=1
  else:break
print(s)

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


#!/usr/bin/python
# -*- coding: utf-8 -*-

s = raw_input()
n, x =  [int(i) for i in s.split()]

aa = raw_input()
a = [int(i) for i in aa.split()]

a = sorted(a)
count = 0
total = 0
for i in a:
    total += i
    if total > x:
        break
    count += 1
print count
#17024977 | shenweiqiang's solution for [AtCoder-4375] [Problem E]


import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    K = I()

    ans = (K // 2) * (K - K // 2)
    print(ans)

if __name__ == '__main__':
    resolve()

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


def main():
    x1, y1, x2, y2 = map(int, input().split())
    y = y2-y1
    x = x2-x1
    print(x2-y, y2+x, x1-y, y1+x)

if __name__ == '__main__':
    main()

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


x1, y1, x2, y2 = list(map(int, input().split()))
d = y1 - y2
print(x2 + d, y2, x2 + d, y1)


H,W =map(int,input().split())

a=[list(input()) for i in range(H)]
l_idx=[]
c_idx=[]
for i in range(H):
    for j in range(W):
        if a[i][j]=="#":
            l_idx.append(i)
            c_idx.append(j)

for i in range(W-1,-1,-1):
    if not i in c_idx:
        for j in range(H):
            a[j].pop(i)

for i in range(H):
    if i in l_idx:
        print("".join(a[i]))

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

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

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

4 5
.....
.....
..#..
.....

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#


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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache

#############
# Constants #
#############

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

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0:
        cnt+=1
        temp //= i
      arr.append([i, cnt])
  if temp!=1:
    arr.append([temp, 1])
  if arr==[]:
    arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i:
        divisors.append(n//i)
  return divisors

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

N,K = IL()
X = IL()

if 0 in X:
  X.remove(0)
  K -= 1
  N -= 1

if K==0:
  print(0)
  E()

p = bisect.bisect(X,0)
count = []

dic = DD(lambda:(INF,INF))
dic_gyaku = DD(lambda:INF)
for i in range(N):
  dic[X[i]]=(max(p-i,i-p+1),-1 if i<p else 1)
  dic_gyaku[(max(p-i,i-p+1),-1 if i<p else 1)] = X[i]

MIN = INF
for i in range(N):
  num, sign = dic[X[i]]
  if sign < 0:
    left = K-num
    if left > 0:
      MIN = min(MIN,abs(X[i])*2+abs(dic_gyaku[(left,1)]))
    else:
      MIN = min(MIN,abs(X[i]))
  else:
    left = K-num
    if left > 0:
      MIN = min(MIN,abs(X[i])*2+abs(dic_gyaku[(left,-1)]))
    else:
      MIN = min(MIN,abs(X[i]))
print(MIN)

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

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

Sample Output 4

10


N, K = map(int, input().split())
x = list(map(int,input().split()))
ans = 10**9
if N == 1:
    ans = abs(x[0])
for i in range(N-K):
    ans = min(ans, abs(x[i])+abs(x[i+K-1]-x[i]), abs(x[i+K-1])+abs(x[i]-x[i+K-1]))
print(ans)


import bisect

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

idx = bisect.bisect_left(x,0)

ans = 10**100

for i in range(k):
    #print(idx-i,idx+k-1-i)
    if i == 0 and idx+k-1 < n:
        ans = min(ans, x[idx+k-1])
    elif idx - i < 0 or idx+k-1-i >= n:
        continue
    else:
        ans = min(ans, - 2*x[idx-i] + x[idx+k-1-i])
        ans = min(ans, - x[idx-i] + 2*x[idx+k-1-i])

print(ans)


S = input()
K = int(input())
if K <= len(S):
    is_all_one = 1
    num = 0
    for i in range(K):
        if S[i] != "1":
            is_all_one = 0
            num = S[i]
            break
    if is_all_one:
        print(1)
    else:
        print(num)
else:
    is_all_one = 1
    num = 0
    for i in range(len(S)):
        if S[i] != "1":
            is_all_one = 0
            num = S[i]
            break
    print(num)

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


s=input()
k=int(input())
l=0
for i in s:
    if i=="1":
        l+=1
    else:
        break
print("1" if k<=l else s[l])


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

if len(S) == 1:
    print(S)
else:
    if K == 1:
        print(1)
    else:
        print(2)


# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 21:50:39 2018
ABC106D
@author: maezawa
"""
import bisect
n, m, qn = list(map(int, input().split()))

lr = []

for i in range(m):
    lri = list(map(int, input().split()))
    lr.append(lri)

lr.sort(key=lambda x:(x[0],x[1]))
l = [z[0] for z in lr]

for i in range(qn):
    pi, qi = list(map(int, input().split()))
    idxl =  bisect.bisect_left(l, pi)
    lrtmp2 = [z[1] for z in lr[idxl:]]
    lrtmp2.sort()
    idxr = bisect.bisect_right(lrtmp2, qi)
    print(idxr)

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

N is an integer between 1 and 500 (inclusive).

M is an integer between 1 and 200 \ 000 (inclusive).

Q is an integer between 1 and 100 \ 000 (inclusive).

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


n,k = map(int,input().split())
if n%k ==0:
  print(0)
elif n < k:
  print((1)
else:
  print((n//k) - 1)

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


n = int(input())
print('Yes' if any(4*i+7*j==n for i in range(26) for j in range(15)) else 'No')

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


n = int(input())
print("Yes" if [1 for a in range(n//7+1) for b in range(n//4+1) if a*7+b*4 == n] else "No")


n=int(input())
if(n<1200):
    print("ABC")
elif(n<2800):
    print("ARC")
else:
    print("AGC")

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


x = int(input())
if x < 1200:
	print("ABC")
elif 1200<= x <2800:
	print("ARC")
else:
	print("AGC")


from sys import stdin

S = stdin.readline().rstrip()

cond1 = S[0] == 'A'
cond2 = S.count('C', 2, -2) == 1
cond3 = S.replace('A', '').replace('C', '').islower()

if cond1 and cond2 and cond3:
    print('AC')
else:
    print('WA')

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


import re
s = input()
c = 'C'
if s[0].isupper():
    S = s[2:-2]
    if S.count('C') == 1 or (S == '' and s[2] == 'C'):
        if len(re.findall('[a-z]', s)) == len(s) - 2:
            print('AC')


d,g=map(int,input().split())
l=[list(map(int,input().split())) for i in range(d)]
cnt=30000
for i in range(2**d):
    cntd=0
    div=i
    score=0
    allsolved=[False]*d
    for j in range(d)[::-1]:
        if div//(2**j):
            allsolved[j]=True
            cntd+=l[j][0]
            score+=100*(j+1)*l[j][0]+l[j][1]
        div%=(2**j)
    rem=max(0,g-score)
    for h in range(d)[::-1]:
        if allsolved[h]:continue
        if rem<=100*(h+1)*(l[h][0]-1):
            cntd+=(rem+100*(h+1)-1)//(100*(h+1))
            rem=0
            break
        else:
            cntd+=l[h][0]-1
            rem-=100*(h+1)*(l[h][0]-1)
    if rem<=0 and cntd < cnt:cnt=cntd
print(cnt)

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


#!/usr/bin/env python3
import sys
from math import ceil

def solve(D: int, G: int, p: "List[int]", c: "List[int]"):
    answer = 1000
    ## どの問題を全部解くか全探索
    for i in range(2**D):
        tmpans = 0
        score = 0
        com_problem = []

        for j in range(D):
            if i & 1<<j:
                score += p[j]*100*(j+1)+c[j]
                tmpans += p[j]
                com_problem.append(j)
        if score >= G:
            answer = min(answer,tmpans)
        else:

            for probrem_index in range(D-1,-1,-1):
                if probrem_index in com_problem:
                    continue

                if (G-score)>100*(probrem_index+1)*(p[probrem_index]-1):
                    break
                else:
                    tmpans += ceil((G-score) / (100*(probrem_index+1)))
                    answer = min(answer,tmpans)
                    break

    print(answer)

    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    D = int(next(tokens))  # type: int
    G = int(next(tokens))  # type: int
    p = [int()] * (D)  # type: "List[int]"
    c = [int()] * (D)  # type: "List[int]"
    for i in range(D):
        p[i] = int(next(tokens))
        c[i] = int(next(tokens))
    solve(D, G, p, c)

if __name__ == '__main__':
    main()


# coding: utf-8
# Your code here!

import copy

class Problem:
    def __init__(self, i, num, comp):
        self.point = (i + 1) * 100
        self.num = num
        self.comp = comp
        self.total = (i + 1) * 100 * num + comp
        self.per = self.total / self.num

nums=list(map(int,input().split()))
D = nums[0]
G = nums[1]
problems= []
for i in range(D):
    nums=list(map(int,input().split()))
    problems.append(Problem(i, nums[0], nums[1]))

min_num = 1000

for i in range(D):
    level = copy.deepcopy(problems)
    tmp_comp = sorted(problems, key=lambda u: u.per)
    sm = 0
    sm_num = 0
    res = []
    for _ in range(i):
        tmp_comp.pop()

    while len(tmp_comp) != 0 and G - sm > 0:
        tmp_problem = tmp_comp.pop()

        if G - sm < level[-1].point * level[-1].num:
            cnt = level[-1].num
            while G - sm > 0 and cnt > 0:
                sm += level[-1].point
                sm_num += 1
                cnt -= 1
            if min_num > sm_num:
                min_num = sm_num
                break
        elif tmp_problem.per > level[-1].point:
            sm += tmp_problem.total
            sm_num += tmp_problem.num
            level = sorted(tmp_comp, key=lambda u: u.point)

        else:
            res.append(tmp_problem)

    res.sort(key=lambda u: u.point)

    while sm < G and len(res) != 0:
        tmp_problem = res.pop()
        for i in range(tmp_problem.num):
            sm += tmp_problem.point
            sm_num += 1
            if sm >= G:
                break

    if min_num > sm_num and G <= sm:
        min_num = sm_num

print(min_num)


d, g = map(int, input().split())
p = [0] * (d+1)
c = [0] * (d+1)
maximum = 10 * 100 + 1

for i in range(1, d+1):
    p[i], c[i] = map(int, input().split())

def dfs(i, score, count):
    if i > d:
        if score >= g:
            return count
        else:
            return maximum
    elif score >= g:
        return count
    else:
        ans = []
        for j in range(0, p[i]+1):
            next_score = score + 100 * i * j
            if j == p[i]:
                next_score += c[i]
            ans.append(dfs(i+1, next_score, count+j))
        return min(ans)

print(dfs(1, 0, 0))


D, G = map(int,input().split(' '))
pc = [list(map(int,input().split(' '))) for i in range(D)]

ans = 0
for i in range(D):
    ans += pc[i][0]

for i in range(2**D-1):
    temp_ans = 0
    temp_sum = 0
    s = '{:010b}'.format(i)[::-1]
 #   print(s)
    notused = -1
    for j in range(D):
        if s[j] == '1':
            temp_ans += pc[j][0]
            temp_sum += (j+1)*pc[j][0]*100 + pc[j][1]
        else:
            notused = j
#    print(notused,temp_ans,temp_sum)
    if temp_sum >= G:
        ans = min(temp_ans,ans)
    else:
        for i in range(1,pc[notused][0]):
            if (notused+1)*i*100+temp_sum >= G:
                ans = min(temp_ans+i,ans)
#                print(ans)
                break
print(ans)


S = input()
T = input()
word = [x for x in T]
for i in range(len(word)):
    a = word[0]
    word.append(a)
    word.remove(a)
    if S == word:
        break
    else:
        pass
if S == word:
    print('Yes')
else:
    print('No')

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


a=input()
b=input()

flag=0
if a==b:
    flag=1
else:
    for i in range(len(a)):
        a=a[-1:]+a[:-1]
        if a==b:
            flag=1
            break

if flag==1:
    print('Yes')
elif flag==0:
    print('No')


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

def func(m,AS):
  ans = 0
  for a in AS:
    ans += (m % a)
  return ans

ans = 0
for i in range(2,10**5+1):
  a = func(i,AS)
  if a > ans:
    ans = a
print(ans)

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


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


import math
from functools import reduce

def lcm_base(x, y):
    return (x * y) // math.gcd(x, y)
def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

N = int(input())
a = list(map(int, input().split()))
lcm = lcm(*a)-1
f = 0
for i in range(len(a)):
    f += lcm%a[i]
print(f)


n,m = map(int,input().split())
a = [list(map(int,input().split())) for _ in range(m)]
a = sorted(a,key=lambda x:x[1])
ans = [0]
for a_ in a:
    for i,k in enumerate(ans):
        if a_[0]<k and a_[1]>=k:
            break
        elif i==len(ans)-1:
            ans.append(a_[1])
            break
print(len(ans)-1)

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

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

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4


_, M = map(int, raw_input().split())
lst = []

for i in range(M):
    a, b = map(int, raw_input().split())
    lst.append((b, a))

lst.sort()
print lst
pos = 0
ans = 0

for p in lst:
    if p[1] >= pos:
        ans += 1
        pos = p[0]
print ans


from itertools import chain
N, M = [int(x) for x in input().split()]

ab = [(int(x[0]), int(x[1])) for _ in range(M) for x in [input().split()]]

def mode(X):
    return max([(X.count(x), x) for x in set(X)], key=lambda x: x[0])[1]

count = 0
while ab:
    X = list(chain.from_iterable([list(range(x[0], x[1])) for x in ab]))
    m = mode(X)
    ab = [x for x in ab if m < x[0] or x[1] <= m]
    count += 1
print(count)


from fractions import gcd
from functools import reduce
def gcds(*numbers):
  return reduce(gcd, numbers)
n = int(input())
for i in range(n):
  a,b,c,d = map(int,input().split())
  x = gcds(a,b,c,d)
  if x != 1:
    a = a//x
    b = b//x
    c = c//x
    d = d//x
  if b>d or a<b:
    print("No")
  elif c>=b-1:
    print("Yes")
  elif gcd(b,d) != 1:
    y = gcd(b,d)
    if b-c<y and c%y >= a%y:
        print("Yes")
    else:
      print("No")
  else:
    print("No")

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


def main():
    t = int(input())
    A=[]
    B=[]
    C=[]
    D=[]

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

    for i in range(t):
        ans = "yes"

        if A[i] < B[i] or B[i] > D[i]:
            ans = "no"

        for j in range(B[i]):
            if (A[i] + (j*D[i])) % B[i] > C[i]:
                ans = "no"

        print(ans)

if __name__ == "__main__":
        main()


N = int(input())
if N % 2 == 0:
    print(N)
else:
    print(2*N)

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


n=int(input())
al=list(map(int,input().split()))
t=[]
for i in range(n):
    t.append(al[i]-(i+1))
t=sorted(t)
if n%2==0:
    v=(t[n//2-1]+t[n//2])//2
else:
    v=t[n//2]
ans=0
for i in t:
    ans+=abs(i-v)
print(ans)

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


n,k = map(int, input().split())
a  = [int(i) for i in input().split()]

import math
print(math.ceil((n-1) / (k-1)))

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


import sys
import math
def I():return int(sys.stdin.readline().replace("\n",""))
def I2():return map(int,sys.stdin.readline().replace("\n","").split())
def S():return str(sys.stdin.readline().replace("\n",""))
def L():return list(sys.stdin.readline().replace("\n",""))
def Intl():return [int(k) for k in sys.stdin.readline().replace("\n","").split()]
def Lx(k):return list(map(lambda x:int(x)*-k,sys.stdin.readline().replace("\n","").split()))

if __name__ == "__main__":
    n ,k = I2()
    a = Intl()
    #minは1なのである要素から1までの距離を考えて、それをk-1で割った商が置き換え回数
    cnt = 0
    r = a.index(1)
    first = r#先頭から1までの距離
    end = n-r-1#末尾から1までの距離
    #print(first,end)
    cnt += math.ceil(first/(k-1))
    cnt += math.ceil(end/(k-1))
    print(cnt)


import math

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

ml=[i for i, v in enumerate(A) if v == min(A)]
tmp=0

tmp+=math.ceil(ml[0]/(K-1))
for i in range(len(ml)-2):
    tmp+=math.ceil((ml[i+1]-ml[i]-1)/(K-1))
tmp+=math.ceil((N-ml[len(ml)-1]-1)/(K-1))
print(tmp)


A, B = map(int, input().split())
print('Yay!' if A < 9 and B < 9 else ':(')

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


import collections
N, M = map(int, input().split())
x = [[0, 0] for i in range(N)]
y = [[0, 0] for i in range(N)]
z = [[0, 0] for i in range(N)]
xyz = [list(map(int, input().split())) for i in range(N)]
for i in range(N):
    x[i][0], y[i][0], z[i][0] = xyz[i][0], xyz[i][1], xyz[i][2]
    x[i][1], y[i][1], z[i][1] = i, i, i

ans = 0
for k in range(2**3):
    flag = [1, 1, 1]
    tmp = [0, 0, 0]
    for l in range(3):
        if (k >> l) % 2 == 1:
            flag[l] = -1
        else:
            flag[l] = 1
    # print(flag)
    xyz.sort(reverse=True, key=lambda x: x[0]
             * flag[0] + x[1]*flag[1] + x[2]*flag[2])

    for i in range(M):
        tmp[0] += xyz[i][0]
        tmp[1] += xyz[i][1]
        tmp[2] += xyz[i][2]
    # print(abs(tmp[0]) + abs(tmp[1]) + abs(tmp[2]))
    # print(xyz)
    ans = max(ans, abs(tmp[0]) + abs(tmp[1]) + abs(tmp[2]))
print(ans)

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

N is an integer between 1 and 1 \ 000 (inclusive).

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


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

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


def f(x):
    if x == 0:
        return 0
    return x + f(x - 1)

a, b = map(int, input().split())
x = b - a
ans = f(x) - b

print(ans)


a, b = map(int, input().split())
nl = 0
c = 0
for i in range(1, 999):
    nl += i
    if nl > a:
        break
for j in range(1, 1000):
    nl += j
    if nl > b:
        break
print(nl - b)


Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


N=int(input())
INF=10**9
dp=[INF]*(N+1)#dp[i] 足場i+1にいるときの最小コスト
dp[0]=0
list=[1]
i=1
while(6**i<=N):
    list.append(6**i)
    i+=1
i=1
while(9**i<=N):
    list.append(9**i)
    i+=1
for i in range(N+1):
    for k in list:
        if i+k<=N:
            dp[i+k]=min(dp[i+k],1+dp[i])
print(dp[N])


n = int(input())

ans = 10**10
for a in range(6):
    for b in range(3):
        for c in range(6):
            for d in range(6):
                for e in range(6):
                    for f in range(6):
                        for g in range(2):
                            for h in range(4):
                                for i in range(8):
                                    for k in range(9):
                                        for l in range(9):
                                            for m in range(2):
                                                if 1*a + 6*b + 36*c + 6**3*d + 6**4*e + 6**5*f + 6**6*g + 9*h + 9**2*i + 9**3*k + 9**4*l + 9**5*m == n:
                                                    ans = min(ans, a+b+c+d+e+f+g+h+i+k+l+m)
print(ans)


s=sum(list(input()))
print(10 if s==1 else s)

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


a, b = map(int, input().split())
ans = max(a+b, a-b, a*b)
print(ans)

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


import numpy as np
n = int(input())
s = input()

cnt = 0
for i in range(1,n):
  tmp = 0
  for a in set(list(s[:i])):
    tmp += max(np.sign(s[i:].find(a)+0.5),0)
  cnt = max(cnt,tmp)
print(int(cnt))

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


class unionFind():
	def __init__(self,n):
		self.tree=[-1]*n
	def find(self,x):
		if self.tree[x]<0:
			return x
		else:
			self.tree[x]=self.find(self.tree[x])
			return self.tree[x]
	def union(self,x,y):
		xr=self.find(x)
		yr=self.find(y)
		if xr!=yr:

			if self.tree[xr]==self.tree[yr]:
				self.tree[xr]-=1
				self.tree[yr]=xr
			elif self.tree[xr]>self.tree[yr]:
				self.tree[xr]=yr
			else:
				self.tree[yr]=xr
			return True

		return False
def main():
	ans=0
	n,m=map(int,input().split())
	a=unionFind(n)
	li=[x-1 for x in list(map(int,input().split()))]
	for _ in range(m):
		x,y=map(int,input().split())
		a.union(x-1,y-1)
	for x in range(n):
		ans += a.find(x)==a.find(li[x])
	return ans
print(main())

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

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

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


import sys
from collections import Counter
import random
import time
import math

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

n=int(input())
a=list(map(int,input().split()))
S=[sum(a[:i])for i in range(n+1)]
s=set(S)
c=0
for i in s:
    nu=S.count(i)
    if(nu>1):c+=comb(nu,2)
print(c)

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

-10^9 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


import functools
import operator

N = int(input())
a = list(map(int, input().split()))
s = 0
for max_num in range(2, N):
    for index in range(N - max_num + 1):
        if 0 == functools.reduce(operator.add, a[index: index + max_num]):
            s += 1

print(s)


n = int(input())
s = []
for _ in range(n):
    sw = input()
    s.append([c for c in sw])

def val(s,k):
    global n
    for i in range(n):
        for j in range(n):
            if i+k >= n:
                ni = i+k-n
            elif i+k < 0:
                ni = i+k+n
            else:
                ni = i+k
            if j-k >= n:
                nj = j-k-n
            elif j-k < 0:
                nj = j-k+n
            else:
                nj = j-k

            if s[i][j] != s[nj][ni]:
                return False
    return True

res = 0
for k in range(0,n):
    if val(s,k):
        res += n
print(res)

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


a,b,c,x,y = map(int,input().split())
price1 = 0
price2 = 0
price = 0
if (a+b) >= c*2:
    price1 += min(x,y) * 2 * c
    if min(x,y)==x:
        price1 += (y-x)*b
    else:
        price1 += (x-y)*a

    price2 += c * max(x,y) *2
    price = min(price1,price2)
else:
    price += (a*x + b*y)
print(price)

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


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

print(min(A+B, C*2) * min(X,Y) + (X - min(X,Y)) * min(A, C*2) + (Y - min(X,Y)) * min(B, C*2))


A,B,C,X,Y=map(int,input().split())
ans=0
if 2*C<A+B:
  Z=min(X,Y)
  X-=Z
  Y-=Z
  ans+=2*C*Z
A=min(A,2*C)
B=min(B,2*C)
ans+=A*X
ans+=B*Y
print(ans)


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

print("YES" if A+B >= X and A <= X else "NO")

Score : 100 points

Problem Statement

There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.

Determine if it is possible that there are exactly X cats among these A + B animals.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.

Sample Input 1

3 5 4

Sample Output 1

YES

If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.

Sample Input 2

2 2 6

Sample Output 2

NO

Even if all of the B = 2 animals are cats, there are less than X = 6 cats in total.

Sample Input 3

5 3 2

Sample Output 3

NO

Even if all of the B = 3 animals are dogs, there are more than X = 2 cats in total.


N, M, X = map(int, input().split())
A = [int(a) for a in input().split()]

L = len([a for a in A if a < X ])
R = len(A) - L

print(min(L, R))

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3


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

mr=Y[N//2]
ml=Y[N//2-1]

for x in X:
    if mr<=x:
        print(ml)
    else:
        print(mr)

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


import statistics
N = int(input())
Xlist = list(map(int, input().split()))
for i in range(N):
    a = Xlist[0:i] + Xlist[i + 1:]
    print(statistics.median(a))


# -*- coding: utf-8 -*-
n = int(input())
x = [int(i) for i in input().split()]
xx = sorted(x)
mid = n//2-1

d = {}
for i in range(n):
    if i<=mid:
        d[xx[i]] = xx[mid+1]
    else:
        d[xx[i]] = xx[mid]

for i in range(n):
    print(d[x[i]])


Score : 100 points

Problem Statement

You are given a string S of length 3 consisting of a, b and c. Determine if S can be obtained by permuting abc.

Constraints

|S|=3

S consists of a, b and c.

Input

Input is given from Standard Input in the following format:

S

Output

If S can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No


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

if b-a <= k:
    L = list(range(a,b+1))
else:
    i = list(range(a,a+k))
    j = list(range(b-k+1,b+1))

    L = list(set(i+j))
    L = sorted(L)

for i in L:
    print(i)

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


# coding : utf-8

import numpy as np

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

if((B-A+1) > 2*C):
	for i in range(C):
		print(A + i)
	for i in range(C):
		print(B + i - C + 1)
else:
	for i in range(A,B+1):
		print(i)


Score : 300 points

Problem Statement

You are given three integers A, B and C. Find the minimum number of operations required to make A, B and C all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among A, B and C, then increase both by 1.

Choose one among A, B and C, then increase it by 2.

It can be proved that we can always make A, B and C all equal by repeatedly performing these operations.

Constraints

0 \leq A,B,C \leq 50

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the minimum number of operations required to make A, B and C all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make A, B and C all equal by the following operations:

Increase A and C by 1. Now, A, B, C are 3, 5, 5, respectively.

Increase A by 2. Now, A, B, C are 5, 5, 5, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23


temp = list(map(int, input().split()))
temp.sort()
a, b, c = temp[0], temp[1], temp[2]
count = 0

while(c - b > 1):
    b += 2
    count += 1

while(b - a > 1):
    a += 2
    count += 1

if a == b == c: print(count)
elif c - b == 1 and b - a == 1: print(count + 3)
elif c - b == 1 and b - a == 0: print(count + 1)
else: print(count + 2)


S = input()

if len(S) < 26:
    for i in range(26):
        if chr(i+97) not in S:
            ans = S + chr(i+97)
            break
elif S == "zyxwvutsrqponmlkjihgfedcba":
    ans = -1
else:
    ans = ""
    for i in range(24, -1, -1):
        if S[i+1] > S[i]:
            for j in range(i):
                ans += S[j]
            ans += S[-1]
            break
print(ans)

Score : 300 points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 \leq |S| \leq 26

S is a diverse word.

Input

Input is given from Standard Input in the following format:

S

Output

Print the next word that appears after S in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx


s = input()
MAX = 'zyxwvutsrqponmlkjihgfedcba'
lst_s = list(s)

if len(s) != 26:
    AL = [chr(i) for i in range(97, 123)]
    for i in range(len(s)):
        AL.remove(lst_s[i])
    ans = s + AL[0]
elif s == MAX:
    ans = -1
else:
    count = 0
    for i in range(24, 0, -1):
        if s[i] < min(lst_s[i+1:]):
            lst_s[i] = min(lst_s[i+1:])
            ans = ''.join(lst_s[:i+1])
            break
print(ans)


# coding: utf-8
# Your code here!
eng_li = []
removed_list = []
all_letter = 26
for i in range (97,97+all_letter):
    eng_li.append(chr(i))

string = list(raw_input().strip())
length = len(string)
if length < all_letter:
    for i in string:
        eng_li.remove(i)
    string.append(eng_li[0])
    answer = "".join(string)
else:
    for i in range(all_letter-1):
        if ord(string[-1]) < ord(string[-2]) :
            removed_list.append(string[-1])
            string.pop()
        else:
            removed_list.append(string[-1])
            string.pop()
            removed_list=filter(lambda x:x>string[-1],sorted(removed_list))
            string.pop()
            string.append(removed_list[0])
            answer ="".join(string)
            break
    else:
        answer = -1
print answer


s = list(input())
if sorted(s, reverse=True) == s and len(s) == 26:
    print(-1)
    quit()
sn = []
for i in s:
    sn.append(ord(i)-97)
for i in range(1, 26+1):
    if i not in sn:
        if len(s) != 26:
            print(''.join(s) + chr(97+i))
            quit()
ans = []
for j in range(len(s)):
    ans.append(chr(97 + j))
    if sn[j] != j:
        print(''.join(ans))
        quit()


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

a, b, c, d = [int(readline()) for _ in range(4)]
print(min(a, b)+min(c, d))

Score : 100 points

Problem Statement

You planned a trip using trains and buses.
The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket.
Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.

Find the minimum total fare when the optimal choices are made for trains and buses.

Constraints

1 \leq A \leq 1 000

1 \leq B \leq 1 000

1 \leq C \leq 1 000

1 \leq D \leq 1 000

All input values are integers.

Input

Input is given from Standard Input in the following format:

A
B
C
D

Output

Print the minimum total fare.

Sample Input 1

600
300
220
420

Sample Output 1

520

The train fare will be 600 yen if you buy ordinary tickets, and 300 yen if you buy an unlimited ticket.
Thus, the optimal choice for trains is to buy an unlimited ticket for 300 yen.
On the other hand, the optimal choice for buses is to buy ordinary tickets for 220 yen.

Therefore, the minimum total fare is 300 + 220 = 520 yen.

Sample Input 2

555
555
400
200

Sample Output 2

755

Sample Input 3

549
817
715
603

Sample Output 3

1152


# ARC093C - Traveling Plan
def main():
    N = int(input())
    A = list(map(int, input().rstrip().split()))
    for i in range(N):
        ans = 0
        cur = 0
        for j in range(N):
            if i == j:
                continue
            ans += max(cur, A[j]) - min(cur, A[j])
            cur = A[j]
    print(ans + abs(cur))

if __name__ == "__main__":
    main()

Score : 300 points

Problem Statement

There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N.
Spot i is at the point with coordinate A_i.
It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate 0, then visit the N spots in the order they are numbered, and finally return to the point with coordinate 0.

However, something came up just before the trip, and you no longer have enough time to visit all the N spots, so you decided to choose some i and cancel the visit to Spot i.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate 0 at the beginning and the end, as planned.

For each i = 1, 2, ..., N, find the total cost of travel during the trip when the visit to Spot i is canceled.

Constraints

2 \leq N \leq 10^5

-5000 \leq A_i \leq 5000 (1 \leq i \leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N lines.
In the i-th line, print the total cost of travel during the trip when the visit to Spot i is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot 1, 2 and 3 are at the points with coordinates 3, 5 and -1, respectively.
For each i, the course of the trip and the total cost of travel when the visit to Spot i is canceled, are as follows:

For i = 1, the course of the trip is 0 \rightarrow 5 \rightarrow -1 \rightarrow 0 and the total cost of travel is 5 + 6 + 1 = 12 yen.

For i = 2, the course of the trip is 0 \rightarrow 3 \rightarrow -1 \rightarrow 0 and the total cost of travel is 3 + 4 + 1 = 8 yen.

For i = 3, the course of the trip is 0 \rightarrow 3 \rightarrow 5 \rightarrow 0 and the total cost of travel is 3 + 2 + 5 = 10 yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288