n,h = map(int,input().split())
al = []
bl = []
ans = 0
for i in range(n):
    a,b = map(int,input().split())
    al += [a]
    bl += [b]
am = max(al)
bl.sort(reverse=1)
for i in bl:
    if i>am:
        ans += 1
        h -= i
    else:
        break
if h > 0:
    ans += (h+am-1) // am
print(ans)

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have N katana (swords), Katana 1, Katana 2, …, Katana N, and can perform the following two kinds of attacks in any order:

Wield one of the katana you have. When you wield Katana i (1 ≤ i ≤ N), the monster receives a_i points of damage. The same katana can be wielded any number of times.

Throw one of the katana you have. When you throw Katana i (1 ≤ i ≤ N) at the monster, it receives b_i points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.

The monster will vanish when the total damage it has received is H points or more. At least how many attacks do you need in order to vanish it in total?

Constraints

1 ≤ N ≤ 10^5

1 ≤ H ≤ 10^9

1 ≤ a_i ≤ b_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N H
a_1 b_1
:
a_N b_N

Output

Print the minimum total number of attacks required to vanish the monster.

Sample Input 1

1 10
3 5

Sample Output 1

3

You have one katana. Wielding it deals 3 points of damage, and throwing it deals 5 points of damage. By wielding it twice and then throwing it, you will deal 3 + 3 + 5 = 11 points of damage in a total of three attacks, vanishing the monster.

Sample Input 2

2 10
3 5
2 6

Sample Output 2

2

In addition to the katana above, you also have another katana. Wielding it deals 2 points of damage, and throwing it deals 6 points of damage. By throwing both katana, you will deal 5 + 6 = 11 points of damage in two attacks, vanishing the monster.

Sample Input 3

4 1000000000
1 1
1 10000000
1 30000000
1 99999999

Sample Output 3

860000004

Sample Input 4

5 500
35 44
28 83
46 62
31 79
40 43

Sample Output 4

9


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

X = [list(map(int,input().split())) for _ in range(N)]
X = sorted(X,key=lambda X:-X[0])
a = X[0][0]
X = sorted(X,key=lambda X:-X[1])

i = 0
count = 0
while M > 0:
	if i < N and X[i][1] > a:
		M -= X[i][1]
		i += 1
	else:
		count += -(-M//a)
		break
	count += 1

print(count)

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

Submitted source-code file size, in bytes.

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

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


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

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

A=sorted(A)
B=sorted(B)

idx=bisect.bisect_right(B,A[-1])
throw=sum(B[idx:])
if throw<=H:
    ans=N-idx
    res=H-throw
    ans+=ceil(res/A[-1])
    #print(res/A[-1], throw)
else:
    res=H
    ans=0
    for i in range(N):
        ans+=1
        res-=B[i]
        if res<=0:
            break
print(ans)


N,H=map(int,input().split())
B=[]
index=-1
tmp=-1
for i in range(N):
  a,b=map(int,input().split())
  B.append(b)
  if a>tmp:
    index=i
    tmp=a
a_,b_=tmp,B[index]
cnt=0
B=sorted(B,reverse=True)
while len(B)!=0:
  b=B.pop(0)
  if b<=a_:
    break
  H-=b
  cnt+=1
v=H//a_
if H%a_==0:
  cnt+=v
else:
  cnt+=(v+1)
print(cnt)


import heapq as hq
s=[]
hq.heapify(s) #sをpriority-q化　O(n log(n))
# a=hq.heappop(s)  #最小値を取り出す O(log(n))
# hq.heappush(s,123) #123をs(priority-q)に追加 O(log(n))
n,h=map(int,input().split())
for i in range(n):
    a,b=map(int,input().split())
    hq.heappush(s,(-a,False))
    hq.heappush(s,(-b,True))
ans=1
x,y=hq.heappop(s)
h+=x
while y and h>0:
    x,y=hq.heappop(s)
    h+=x
    ans+=1
if h>0:
    ans+=(h-x-1)//-x
print(ans)


import operator as op
import math

N, H = list(map(int, input().split()))
ab = []
max_a = 0
for i in range(N):
    ab.append([int(i) for i in input().split()])
    max_a = max(max_a, ab[i][0])
ab.sort(key=op.itemgetter(1), reverse=True)
ans = 0
for i in ab:
    if i[1] < max_a:
        print(ans + math.ceil(H / max_a))
        break
    if H < 0:
        print(ans)
        break
    else:
        H -= i[1]
        ans += 1


n,m = [int(i) for i in input().split()]
l = [[int(i) for i in input().split()] for _ in range(n)]
l2 = sorted(l,key = lambda x :x[0])
min_atk = l2[n-1][0]

l3 = [i[1] for i in l if i[1] > min_atk]
ct = 0
for i in l3:
    if m > 0:
        m -= i
        ct += 1
    else:
        break

if m <= 0:
    print(ct)
else:
    q,r = divmod(m,min_atk)
    ct += (m//min_atk) +( 1 if r > 0 else 0 )
    print(ct)


N, H = map(int, input().split())
# N < 10**5
# H < 10**9
# A<=B<=10**9

B = [0]*N
maxA = 0
for i in range(N):
    a, b = [int(x) for x in input().split()]
    B[i] = b
    maxA = max(maxA, a)

# 投げる奴の候補
B = sorted([b for b in B if b > maxA], reverse=True)

cnt = 0
for b in B:
    cnt += 1
    H -= b
    if H <= 0:
        break
if H > 0:
    q, r = divmod(H, maxA)
    cnt += q + (1 if r > 0 else 0)
print(cnt)


import sys
import math
N,H=map(int,input().split())
p=[]
x=[list(map(int,input().split())) for i in range(N)]
a=max(x[i][0] for i in range(N))
for i in range(N):
    if x[i][1]>a: p.append(x[i][1])

p.sort(reverse=True)
for i in range(len(p)):
    H-=p[i]
    if H<=0: print(i+1),sys.exit()

print(len(p)+math.ceil(H/a))


N,H = input().split()
n = int(N)
h = int(H)
da = 0
db = []
for i in range(n):
    a,b = tuple(map(int,input().split()))
    da = max(a,da)
    db.append(b)
db.sort()
#　その都度最大値を持ってくる
#　持ってきたのが2番目の要素なら消す、1番目の要素なら維持する
total = 0
i = 0
while total < h:
    if len(db) == 0:
        i += (h - total)//da
        break
    elif db[-1] >= da:
        total += db.pop()
    else:
        total += da
    i += 1
print(str(i))


import numpy as np
N,H=map(int,input().split())
ab=[input().split() for i in range(N)]
a = [int(ab[i][0]) for i in range(N)]
maxa = max(a)
b = np.array([int(ab[i][1]) for i in range(N)])
b_effective = b[b > maxa]
b = np.sort(b_effective)[::-1]
s = 0
i = 0
while s < Y and i < len(b):
 s += b[i]
 i += 1
rest = H-sum(b_effective)
if rest % maxa == 0:
 d = rest//maxa
else:
 d = rest//maxa + 1
print(i+d)


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

count=0
for i in range(1,n+1):
  li = [int(k) for k in list(str(i))]
  if sum(li)>=a and sum(li)<=b:
    count+=i

print(count)

Score : 200 points

Problem Statement

Find the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Constraints

1 \leq N \leq 10^4

1 \leq A \leq B \leq 36

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).

Sample Input 1

20 2 5

Sample Output 1

84

Among the integers not greater than 20, the ones whose sums of digits are between 2 and 5, are: 2,3,4,5,11,12,13,14 and 20. We should print the sum of these, 84.

Sample Input 2

10 1 2

Sample Output 2

13

Sample Input 3

100 4 16

Sample Output 3

4554


n,a,b=map(int,input().split())
cnt=0
for i in range(1,n+1):
	x=list(str(i))
	x=[int(j) for j in x]
	y=sum(x)
	if a <= y <= b:
		cnt += i
	else:
		pass
print(cnt)


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

def s(x):
  if x < 10:
    return x
  return x%10+s(x//10)

M = [0] * 37

for i in range(1,N+1):
  M[s(i)] += i

print(sum(M[A:B+1]))


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

result = 0
for i in range(n):
    num = sum(int(j) for j in list(str(i + 1)))
    if a <= num <= b:
        result += (i + 1)

print(result)


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

for n in range(1+N):
  if A <= sum([int(s) for s in str(n)]) <= B:
    res += n

print(res)


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

def ketawa(n):
    sum = 0
    while n >= 1:
        sum += n % 10
        n //= 10
    return sum

for i in range(1, N + 1):
    sum = ketawa(i)
    if A <= sum <= B:
        total += i

print(total)


import sys
input = sys.stdin.readline

def sum_digit(n):
    digit_list = list(str(n))
    return sum(map(int, digit_list))

N, A, B = map(int, input().split())
print(sum(filter(lambda x: A <= sum_digit(x) <= B, range(1, N + 1))))


n,a,b= input().split()
N = int(n)
A = int(a)
B = int(b)

ab_list = []
for i in range(1,N+1):
	numbers = list(str(i))
	num_list = list(map(int,numbers))

	sum_numlist = 0
	for j in range(len(num_list)):
		sum_numlist += num_list[j]

	if(A<=sum_numlist and sum_numlist<=B):
		ab_list.append(i)

count = 0
for n in range(len(ab_list)):
	count += ab_list[n]

print(count)


s=input()
ans = 0
for i in range(3):
  if s[i] == '1':
    ans += 1
print(ans)

Score : 100 points

Problem Statement

Snuke has a grid consisting of three squares numbered 1, 2 and 3.
In each square, either 0 or 1 is written. The number written in Square i is s_i.

Snuke will place a marble on each square that says 1.
Find the number of squares on which Snuke will place a marble.

Constraints

Each of s_1, s_2 and s_3 is either 1 or 0.

Input

Input is given from Standard Input in the following format:

s_{1}s_{2}s_{3}

Output

Print the answer.

Sample Input 1

101

Sample Output 1

2

A marble will be placed on Square 1 and 3.

Sample Input 2

000

Sample Output 2

0

No marble will be placed on any square.


#ABC_081_A_Placing_Marbles
a=input(str())
count=0
for i in range(0,3):
	if a[i]=='1':
		count+=1
print(count)


import sys
n = int(input())
lst = list(map(int, input().split()))
res = 0
for p in range(200):
  for i in range(n):
    if lst[i] % 2 == 1:
      print(res)
      sys.exit()
  lst = [int(j / 2) for j in lst]
  res += 1


s = input()
counter = 0
if s[0]=='1':
    counter+=1
if s[1]=='1':
    counter+=1
if s[2]=='1':
    counter+=1

print(counter)


import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

s = input()
print(s.count("1"))


from sys import stdin
s1, s2, s3 = [x for x in list(stdin.readline())]


s = input()

ans = 0

if s[0] == "1":
  ans = ans + 1
if s[1] == "1":
  ans = ans + 1
if s[2] == "1":
  ans = ans + 1

print(ans)


sl = list(input())

print(sl.count("1"))

sl = list(input())

print(sl.count("1"))


s = input()
li = map(int, [s[0], s[1], s[2]])
count = 0
for i in li:
  if i == 1:
    count += 1

print(count)


a = input()

count = 0
for i in a.split():
  if i == 1:
    count += 1

print(count)


import math
s=input()
count=0
if(s[0]=="1"):
    count +=1
if(s[1]=="1"):
    count +=1
if(s[2]=="1"):
    count +=1
print(count)


s = input()
print(len(s.replace('0', '')))


l = input()
t = 0
for c in l:
    if c == '1': t+=1
print(c)


s = input()
t = input()
if len(s) < len(t):
    print("UNRESTORABLE")
    exit()
res = ""

s = s[::-1]
t = t[::-1]
n_s = len(s)
n_t = len(t)
i = 0
cnt = 0
flg = True
while i < n_s:
    if s[i] == '?':
        cnt += 1
        i += 1
    else:
        if s[i] == t[len(t)-1]: # tの先頭文字と同じ
            if n_t-1 < cnt:
                while n_t-1 != cnt:
                    res += 'a'
                    cnt -= 1
            if n_t-1 == cnt and flg:
                for j in range(n_t-1):
                    res += t[j]
                flg = False
            else:
                for j in range(cnt):
                    res += 'a'
        else:
            if n_t < cnt:
                for j in range(n_t):
                    res += t[j]
            else:
                for j in range(cnt):
                    res += 'a'
        res+= s[i]
        cnt = 0
        i += 1
if 0 < cnt:
    for i in range(cnt):
        res+='a'
res = res[::-1]
t = t[::-1]
if t in res:
    print(res)
else:
    print("UNRESTORABLE")

Score : 300 points

Problem Statement

E869120 found a chest which is likely to contain treasure.

However, the chest is locked. In order to open it, he needs to enter a string S consisting of lowercase English letters.

He also found a string S', which turns out to be the string S with some of its letters (possibly all or none) replaced with ?.

One more thing he found is a sheet of paper with the following facts written on it:

Condition 1: The string S contains a string T as a contiguous substring.

Condition 2: S is the lexicographically smallest string among the ones that satisfy Condition 1.

Print the string S.

If such a string does not exist, print UNRESTORABLE.

Constraints

1 \leq |S'|, |T| \leq 50

S' consists of lowercase English letters and ?.

T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T'

Output

Print the string S.

If such a string does not exist, print UNRESTORABLE instead.

Sample Input 1

?tc????
coder

Sample Output 1

atcoder

There are 26 strings that satisfy Condition 1: atcoder, btcoder, ctcoder,..., ztcoder.
Among them, the lexicographically smallest is atcoder, so we can say S = atcoder.

Sample Input 2

??p??d??
abc

Sample Output 2

UNRESTORABLE

There is no string that satisfies Condition 1, so the string S does not exist.


S = input()
T = input()

if len(S) < len(T):
    print("UNRESTORABLE")
    exit()

##一つ一つパターンマッチさせる

ls = len(S)
lt = len(T)
index = -1
for i in range(ls-lt+1):
    cnd = S[i:i+lt]
    flag = True
    for s,t in zip(cnd,T):
        if s != "?":
            if s != t:
                flag = False
                break

    if flag:
        index = i

if index == -1:
    print("UNRESTORABLE")
else:
    tmp = S.replace("?","a")
    print(tmp[:index]+T+tmp[index+lt:])


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

    l = []
    flag = False
    for i in range(len(S)-len(T)+1):
        for s, t in zip(S[i:i+len(T)], T):
            if s != '?' and s != t:
                flag = True
                break
        if flag:
            flag = False
            continue

        l.append(S[:i].replace('?', 'a')+T+S[i+len(T):].replace('?', 'a'))

    if len(l) == 0:
        return 'UNRESTORABLE'
    else:
        l.sort()
        return l[0]

print(solve())


s = input()
t = input()

ans = [None for i in range(len(s))]
for i in range(len(s)):
    ans[i] = s[i]

for i in reversed(range(len(s)-len(t)+1)):
    flag = 0
    for j in range(len(t)):
        if s[i+j]!=t[j] and s[i+j]!="?":
            flag = 1
    if flag == 0:
        for j in range(len(t)):
            ans[i+j]=t[j]
        for j in range(len(s)):
            if ans[j]=="?":
                ans[j]="a"
        print("".join(ans))
        exit()

print("UNRESTORABLE")


s = list(input())
t = list(input())
ans = [-1, -1]
if len(t) <= len(s):
    for i in range(len(s) - len(t) + 1):
        c = 1
        for j in range(len(t)):
            if s[i + j] != "?" and t[j] != s[i + j]:
                c = 0
                break
        if c == 1:
            ans = [i, i + len(t)]

if ans != [-1, -1]:
    k = []
    for i in range(len(s)):
        if ans[0] <= i < ans[1]:
            k.append(t[i - ans[0]])
        else:
            if s[i] == "?":
                k.append("a")
            else:
                k.append(s[i])
    print("".join(k))
else:
    print("UNRESTORABLE")


##Hint for matching: We get the one that has the most match

#For each space in the interval: Match each blank and count it (The T is given to have at most n-1 matches where n is the length of T)

#For absolute match: it has n-1 matches
#For local match: it has the maximum matches

#For no match: The T belongs to the last

#The code is unrestorable if:
    #1) T > S
    #2) code doesn't fit anywhere(?)

S = input()
T = input()
code = S
match = 0
maxmatch = 0
maxmatchloc = -1
hasmatch = False
if (len(T) == 1):
    for x in range(len(S)-1,0,-1):
        if (S[x] == '?'):
            S = S[:x] + T + S[x+1:]
            break
    code = S
    for x in range(len(S)):
        if (S[x] == '?'):
            code = code[:x] + 'a' + code[x+1:]
    print(code)

elif '?' in S:
    if (len(T) <= len(S)):
            for x in range(len(S)-(len(T)-1)):
                match = 0
                for i in range(len(T)):
                    if (S[x+i] == T[i]):
                        if (maxmatch == -1):
                            maxmatch = 0
                        match += 1
                    if (S[x+i] != T[i] and S[x+i] != '?'):
                        maxmatch = -1
                        break
                if (maxmatch == -1 and hasmatch == False):
                    continue
                #if match
                if (match >= maxmatch and maxmatch != -1 and match < len(T)):
                    hasmatch = True
                    maxmatch = match
                    maxmatchloc = x
            #Building the code#
            for x in range(len(S)):
                if (S[x] == '?'):
                    code = code[:x] + 'a' + code[x+1:]
            if (maxmatch == 0):
                code = code[:len(S)-len(T)] + T
                print(code)
            elif(maxmatchloc >= 0):
                code = code[:maxmatchloc] + T + code[maxmatchloc + len(T):]
                print(code)
            elif(maxmatchloc == -1):
                print('UNRESTORABLE')
            else:
                print('UNRESTORABLE')
    else:
        print('UNRESTORABLE')
else:
    print(S)


def solve():
    input_string = input()
    part_string = input()

    for i in range(len(input_string) - len(part_string), -1, -1):
        possible_part_string = input_string[i:i+len(part_string)]  # part_stringの可能性のある文字列
        for j in range(len(part_string) + 1):  # 1つ多くループしているのは最後の処理のため
            if j == len(part_string):
                result = input_string[:i] + part_string + input_string[i + len(part_string):]
                result = result.replace("?", "a")
                print(result)
                return  # 今回のテストケースの終了
            if possible_part_string[j] == "?" or possible_part_string[j] == part_string[j]:
                continue
            else:  # 再度ずらして探索する
                break

    print("UNRESTORABLE")
solve()


s = input()[::-1]
t = input()[::-1]
for i in range(len(s)-len(t)+1):
    for j in range(len(t)):
        if t[j] != s[i+j] != "?":break
    else: break
else:
    print("UNRESTORABLE")
    exit()
s = s[:i] + t + s[i+len(t):]
print(s.replace("?","a")[::-1])


S = list(input())
T = list(input())

index = len(S)
ans = []
isMatch = True

# 後ろから判定
while index - len(T) >= 0:
  obj = S[index - len(T):index]
  # 切り出した文字列がTと一致し得るか判定
  for i in range(len(obj)):
    if not obj[i] == "?" and not obj[i] == T[i]:
      isMatch = False
      break

  # T文字列で埋める
  if isMatch:
    ans.append(S[0:index-len(T)] + T + S[index:])

  isMatch = True
  index = index - 1

if ans == []:
  print("UNRESTORABLE")
else:
  ans = sorted(ans)[0]
  for i in range(len(ans)):
    if ans[i] == "?":
      ans[i] = "a"
      print("".join(ans))


S = list(input())
T = list(input())

if len(S) < len(T):
    print("UNRESTORABLE")

else:
    solved = False
    ind = -1
    for i in reversed(range(len(S) - len(T) + 1)):
        s = S[i:i+len(T)]

        yes = True
        for j in range(len(s)):
            print(T[j], s[j])
            if s[j] == '?' or s[j] == T[j]:
                continue
            else:
                yes = False
                break
        if yes:
            ind = i
            solved = True
            break

    if not solved:
        print("UNRESTORABLE")
    else:
        for i in range(len(S)):
            if i < ind:
                if S[i] == '?':
                    S[i] = 'a'
            elif ind<= i < ind+len(T):
                S[i] = T[i-ind]

    print(''.join(S))


#076-C
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return list(input())
s=S()
t=S()
rest=False
ii=0
for i in range(len(s)-len(t)+1):
    for j in range(len(t)):
        if s[i+j]!=t[j] and s[i+j]!="?":
            break
    else:
        rest=True
        ii=i
if rest:
    for j in range(len(t)):
        s[ii+j]=t[j]
    for i in range(len(s)):
        if s[i]=="?":
            s[i]="a"
    for i in range(len(s)):
        print(s[i],end="")
else:
    print("UNRESTORABLE")


s = input()
t = input()

def ok(i):
    for j in range(len(t)):
        if s[i + j] == '?':
            continue
        elif s[i + j] != t[j]:
            return False
    return True

for i in range(len(s) - len(t), -1, -1):
    if ok(i):
        s = s[:i] + t + s[i + len(t) :]
        s = s.replace('?', 'a')
        print(s)
        import sys
        sys.exit()
print('UNRESTORABLE')


S = input()
T = input()

found = []
for i in range(len(S) - len(T) + 1):
    for cs,ct in zip(S[i:],T):
        if cs != '?' and cs != ct:
            break
    else:
        found.append(i)

if not found:
    print('UNRESTORABLE')
    exit()

ans = 'z' * 51
for i in found:
    tmp = S[:i] + T + S[i+len(T):]
    ans = min(ans, tmp.replace('?', 'a'))
print(ans)


def chk(a,b):
    for (i,j) in zip(a,b):
        if i!=j and i!="?":
            return False
    return True

s=input()
t=input()
n=len(t)
o=""
for i in range(len(s)-n,0,-1):
    if chk(s[i:i+n],t):
        o=s[:i]+t+s[i+n:]
        break
if not o:
    print("UNRESTORABLE")
else:
    print(o.replace("?","a"))


s = input()
t = input()
s,t = s[::-1],t[::-1]
if len(s)<len(t):
	print("UNRESTORABLE")
else:
	for i in range(len(s)-len(t)+1):
		if all(s[i+j]=="?" or s[i+j]==t[j] for j in range(len(t))):
			s = s[:i]+t+s[(i+len(t)):]
			break
	if t not in s:
		print("UNRESTORABLE")
	else:
		answer = s.replace("?","a")[::-1]
		print(answer)


import sys

H, W = map(int, input().split())
l = []
for i in range(H):
  l.append(list(input()))

for i in range(H):
  for j in range(W):
    c=0

    if l[i][j]=="#":
      pass

    else:
      # 左上
      if 0<i and 0<j and l[i-1][j-1]=='#':
        c+=1
      # 上
      if 0<i and l[i-1][j]=='#':
        c+=1
      # 右上
      if 0<i and j<W-1 and l[i-1][j+1]=='#':
        c+=1
      # 左
      if 0<j and l[i][j-1]=='#':
        c+=1
      # 右
      if j<W-1 and l[i][j+1]=='#':
        c+=1
      # 左下
      if i<H-1 and 0<j and l[i+1][j-1]=='#':
        c+=1
      # 下
      if i<H-1 and l[i+1][j]=='#':
        c+=1
      # 右下
      if i<H-1 and j<W-1 and l[i+1][j+1]=='#':
        c+=1

              # 地雷隣接数を記載
      l[i][j]=str(c)

# 出力
for i in range(H):
  print(''.join(l[i]))

Score : 200 points

Problem Statement

You are given an H × W grid.

The squares in the grid are described by H strings, S_1,...,S_H.

The j-th character in the string S_i corresponds to the square at the i-th row from the top and j-th column from the left (1 \leq i \leq H,1 \leq j \leq W).

. stands for an empty square, and # stands for a square containing a bomb.

Dolphin is interested in how many bomb squares are horizontally, vertically or diagonally adjacent to each empty square.

(Below, we will simply say "adjacent" for this meaning. For each square, there are at most eight adjacent squares.)

He decides to replace each . in our H strings with a digit that represents the number of bomb squares adjacent to the corresponding empty square.

Print the strings after the process.

Constraints

1 \leq H,W \leq 50

S_i is a string of length W consisting of # and ..

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the H strings after the process.

The i-th line should contain a string T_i of length W, where the j-th character in T_i corresponds to the square at the i-th row from the top and j-th row from the left in the grid (1 \leq i \leq H, 1 \leq j \leq W).

Sample Input 1

3 5
.....
.#.#.
.....

Sample Output 1

11211
1#2#1
11211

For example, let us observe the empty square at the first row from the top and first column from the left.

There is one bomb square adjacent to this empty square: the square at the second row and second column.

Thus, the . corresponding to this empty square is replaced with 1.

Sample Input 2

3 5
#####
#####
#####

Sample Output 2

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

It is possible that there is no empty square.

Sample Input 3

6 6
#####.
#.#.##
####.#
.#..#.
#.##..
#.#...

Sample Output 3

#####3
#8#7##
####5#
4#65#2
#5##21
#4#310


h, w = map(int, input().split())
l = []
for i in range(h):
    l.append(list(input()))
for i in range(h):
    for j in range(w):
        num_mine = 0
        if l[i][j] != "#":
            if 0<i and 0<j and l[i-1][j-1] == "#":
                num_mine += 1
            if 0<i and l[i-1][j] == "#":
                num_mine += 1
            if 0<i and j<w-1 and l[i-1][j+1] == "#":
                num_mine += 1
            if 0<j and l[i][j-1] == "#":
                num_mine += 1
            if j<w-1 and l[i][j+1] == "#":
                num_mine += 1
            if i<h-1 and 0<j and l[i+1][j-1]== "#":
                num_mine += 1
            if i<h-1 and l[i+1][j] == "#":
                num_mine += 1
            if i<h-1 and j<w-1 and l[i+1][j+1] == "#":
                num_mine += 1
            l[i][j] = str(num_mine)
for i in range(h):
    print(''.join(l[i]))


H, W = map(int, input().split())
S = [list(input()) for _ in range(H)]

dx = [1, 1, 1, 0, 0, -1, -1, -1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]

for h in range(H):
    l = ""
    for w in range(W):
        if S[h][w] == '#':
            l += '#'
            continue
        num = 0
        for d in range(8):
            nx = h + dx[d]
            ny = w + dy[d]
            if nx < 0 or ny < 0 or nx >= H or ny >= W: continue
            if S[nx][ny] == '#' : num+=1
        l+=str(num)
    S[h] = l

for i in range(H):
    print(S[i])


# ABC075B

import numpy as np

h, w = map(int, input().split())
board = sp.reshape(np.array(sp.repeat("@", (h+2)*(w+2))), (h+2, w+2))
for i in range(h):
    s = input()
    board[i+1, 1:w+1] = np.array(list(s))
for i in range(1, h+1):
    count = sp.zeros(w, dtype=str)
    for j in range(1, w+1):
        if board[i,j] == '.':
            count[j-1] = str(\
                (board[i-1, j-1] == "#") + (board[i-1, j] == "#") + (board[i-1, j+1] == "#") +\
                (board[i  , j-1] == "#") + (board[i  , j] == "#") + (board[i  , j+1] == "#") +\
                (board[i+1, j-1] == "#") + (board[i+1, j] == "#") + (board[i+1, j+1] == "#"))
        elif board[i, j] == "#":
            count[j-1] = "#"
    print(''.join(count))


def resolve():
    '''
    code here
    '''
    H, W = [int(item) for item in input().split()]
    grid = [input() for _ in range(H)]

    res = ['' for _ in range(H)]

    def cnt_bomb(i, j):
        cnt = 0

        for n in [-1, 0, 1]:
            for m in [-1, 0, 1]:
                cnt += chk_bomb(i+n, j+m)

        return str(cnt)

    def chk_bomb(i, j):

        if i < 0 or  H <= i or j < 0 or W <= j:
            return 0
        elif grid[i][j] == '#':
            return 1
        else:
            return 0

    for i in range(H):
        for j in range(W):
            if grid[i][j] == '#':
                res[i] += '#'
            else:
                res[i] += cnt_bomb(i, j)

    for line in res:
        print(line)

if __name__ == "__main__":
    resolve()


H,W = map(int,input().split())
S = []
for _ in range(H):
    S.append(input())

ans = []
for i in range(H):
    s = ''
    for j in range(W):
        if S[i][j] == '.':
            count = 0
            for x in [-1,0,1]:
                for y in [-1,0,1]:
                    if 0 <= i+x < H and 0 <= j+y < W:
                        count += 1 if S[i+x][j+y] == '#' else 0
            s += str(count)
        else:
            s += '#'
    ans.append(s)

print(*ans,sep='\n')


W, H = map(int, input().split())
src = [input() for i in range(H)]

ans = []
for row in src:
    ans.append(list(row))

dxy = [(-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1)]
for y in range(H):
    for x in range(W):
        if src[y][x] == '#':
            continue
        c = 0
        for dx,  dy in dxy:
            if x + dx < 0 or x + dx > W - 1 or y + dy < 0 or y + dy > H - 1:
                continue
            if src[y + dy][x + dx] == '#':
                c += 1
        ans[y][x] = c

for row in ans:
    print(''.join(list(map(str, row))))


n = int(input())
count = 0
for _ in range(n):
  a, b = map(int, input().split())
  count += abs(a-b) + 1
print(count)

Score : 200 points

Problem Statement

Joisino is working as a receptionist at a theater.

The theater has 100000 seats, numbered from 1 to 100000.

According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive).

How many people are sitting at the theater now?

Constraints

1≤N≤1000

1≤l_i≤r_i≤100000

No seat is occupied by more than one person.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
l_1 r_1
:
l_N r_N

Output

Print the number of people sitting at the theater.

Sample Input 1

1
24 30

Sample Output 1

7

There are 7 people, sitting at Seat 24,25,26,27,28,29 and 30.

Sample Input 2

2
6 8
3 3

Sample Output 2

4


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

# input
N = int(input())
lr = [list(map(int, input().split())) for i in range(N)]

# solve
ans = 0
for i in range(N):
    ans += lr[i][1] - lr[i][0] + 1

# output
print(ans)


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

def resolve():
    s=input()
    l='abcdefghijklmnopqrstuvwxyz'
    ans='None'
    for i in l:
        if i not in s:
            ans=i
            break
    print(ans)
resolve()

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Find the lexicographically (alphabetically) smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Constraints

1 \leq |S| \leq 10^5 (|S| is the length of string S.)

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the lexicographically smallest lowercase English letter that does not occur in S.
If every lowercase English letter occurs in S, print None instead.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a, but does not contain b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

None

This string contains every lowercase English letter.

Sample Input 3

fajsonlslfepbjtsaayxbymeskptcumtwrmkkinjxnnucagfrg

Sample Output 3

d


s = list(input())
sl = list(int(ord(i)) for i in s)

for i in range(97, 123):
    if sl.count(i) == 0:
        print(chr(i))
        exit()
else:
    print('None')


s = set(input())
alpha = set(map(chr, range(97, 123)))

print(sorted(s^alpha)[0])


s=input()

alp=[chr(i) for i in range(97, 97+26)]
#文字コードで並び替える
s=sorted(set(list(s)))
for i in range(len(s)):
    if s[i]!=alp[i]:
        print(alp[i])
        break
    if i==len(s)-1:
        print("None")


import itertools
from collections import Counter
import bisect

def main():
    s = list(input())
    s = list(set(s))
    s.sort()
    cur = ord('a')
    # print(s)
    for c in s:
        if cur == ord(c):
            cur = cur + 1
        else:
            print(chr(cur))
            exit()
    print('None')

if __name__ == '__main__':
    main()


import string
pp = list(input())
pp=list(set(pp))
pp.sort()
pp.append("1")
print(pp)
s = ""
x = list(string.ascii_lowercase)
x.append("None")
for j in range(len(pp)):
    if pp[j] != x[j]:
        s = x[j]
        break
    elif pp[j] =="1":
        s = "None"
print(s)


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

# AtCoder Beginner Contest
# Problem B

if __name__ == '__main__':
    S = sorted(set(list(input())))
    alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
                 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                 'y', 'z']

    if len(S) == 26:
        print('None')
    else:
        for alphabet in alphabets:
            if alphabet not in S:
                print(alphabet)
                break


s = set(input())
t = [chr(i) for i in range(97, 97+26)]

for c in t:
   if c not in s:
      print(c)
      exit()

print("None")


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

b = sum((i % 2 != 0)  for i in l)
bb = sum((i % 2 == 0)  for i in l)
bbbb  = sum((i % 4 == 0)  for i in l)

bb -= bbbb
if bbbb+1 >= b + (bb == 1):print("Yes")
else:print("No")

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


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

if A > B:
    print(0)
    exit()
elif A == B:
    print(1)
    exit()
else:
    if N == 1:
        print(0)
        exit()

ans = (B * (N - 1) + A) - (A * (N - 1) + B) + 1
print(ans)

Score : 200 points

Problem Statement

Snuke has N integers. Among them, the smallest is A, and the largest is B.
We are interested in the sum of those N integers. How many different possible sums there are?

Constraints

1 ≤ N,A,B ≤ 10^9

A and B are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of the different possible sums.

Sample Input 1

4 4 6

Sample Output 1

5

There are five possible sums: 18=4+4+4+6, 19=4+4+5+6, 20=4+5+5+6, 21=4+5+6+6 and 22=4+6+6+6.

Sample Input 2

5 4 3

Sample Output 2

0

Sample Input 3

1 7 10

Sample Output 3

0

Sample Input 4

1 3 3

Sample Output 4

1


n,a,b=map(int,input().split())
a_=a+b*(n-1)
b_=a*(n-1)+b
if n==1 and a!=b:
  print(0)
elif a>b:
  print(0)
else:
  print(a_-b_+1)


N,A,B=map(int,input().split())
if N > 1 and B >= A:
    k = 1 + (N-2)*(B-A)
    print(k)
elif N == 1 and B == A:
    print(1)
else:
    print(0)


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

    if n == 0:
        ans=0
        print(ans)
        return
    elif n==1:
        if a==b:
            ans=1
            print(ans)
            return
        else:
            ans=0
            print(ans)
            return

    elif n>=2:
        ans=1
        if a>b:
            ans=0
            print(ans)
            return
# ありうる数字の種類
        dif=b-a
        #数
        num=n-2
        ans=dif*num+1
        print(ans)

if __name__ == '__main__':
    main()


n,a,b=map(int,input().split())
if a>b or (n==1 and a!=b):
  print(0)
  exit()
else:
  print((a-b)*max(n-2,0)+1)


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

if (a != b and n == 1) or a > b:
    print(0)
else:
    lowest_pos = a * (n - 1) + b
    highest_pos = a + b * (n - 1)
    print(highest_pos - lowest_pos + 1)


n,a,b=map(int,raw_input().split())
if a>b or (n==1 and a!=b):
    print 0
elif n==1:
    print 1
else:
    print (n-2)*(b-a)+1


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

#A
def A():
    x, y = LI()
    a = [1, 3, 5, 7, 8, 10, 12]
    b = [4, 6, 9, 11]
    c = [2]
    if x in a and y in a:
        print("Yes")
        return
    if x in b and y in b:
        print("Yes")
        return
    if x in c and y in c:
        print("Yes")
        return
    print("No")
    return

#B
def B():
    h, w = LI()
    print("#" * (w + 2))
    for _ in range(h):
        a = ["#"]
        for s in S():
            a.append(s)
        a.append("#")
        print("".join(a))
    print("#" * (w + 2))
    return

#C
def C():
    h, w = LI()
    ans = inf
    for i in range(1, h):
        ans = min(ans, max(i * w, (h - i) * (w // 2), (h - i) * (w - w // 2)) - min(i * w, (h - i) * (w // 2), (h - i) * (w - w // 2)))
        ans = min(ans, max(i * w, (h - i) // 2 * w, (h - i - (h - i) // 2) * w) - min(i * w, (h - i) // 2 * w, (h - i - (h - i) // 2) * w))
    h, w = w, h
    for i in range(1, h):
        ans = min(ans, max(i * w, (h - i) * (w // 2), (h - i) * (w - w // 2)) - min(i * w, (h - i) * (w // 2), (h - i) * (w - w // 2)))
        ans = min(ans, max(i * w, (h - i) // 2 * w, (h - i - (h - i) // 2) * w) - min(i * w, (h - i) // 2 * w, (h - i - (h - i) // 2) * w))
    print(ans)
    return

# D
# 解説AC
# ある点kにおいて2つに分けてa'の
# 前後半の要素を考える
# シンプルにわからなかった
def D():
    n = II()
    a = LI()
    first_half_list = []
    final_half_list = []
    first_half_sum = deque([0])
    final_half_sum = deque([0])
    ans = -inf
    for i in range(n):
        heappush(first_half_list, a[i])
        first_half_sum[0] += a[i]
        heappush(final_half_list, -a[-i - 1])
        final_half_sum[0] -= a[-i - 1]
    for i in range(1, n + 1):
        q = heappop(first_half_list)
        heappush(first_half_list, max(q, a[i + n - 1]))
        first_half_sum.append(first_half_sum[-1] - q + max(q, a[i + n- 1]))
        q = heappop(final_half_list)
        heappush(final_half_list, max(q, -a[-n - i]))
        final_half_sum.appendleft(final_half_sum[-1] - q + max(q, -a[-n - i]))
    for i in range(n + 1):
        ans = max(ans, first_half_sum[i] + final_half_sum[i])
    print(ans)
    return

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

Score : 500 points

Problem Statement

Let N be a positive integer.

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

Find the maximum possible score of a'.

Constraints

1 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Partial Score

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

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the maximum possible score of a'.

Sample Input 1

2
3 1 4 1 5 9

Sample Output 1

1

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

Sample Input 2

1
1 2 3

Sample Output 2

-1

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

Sample Input 3

3
8 2 2 7 4 6 5 3 8

Sample Output 3

5

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


import itertools
import datetime
from heapq import heapify,heappush,heappop

N=input()
a=[]
a=map(int, raw_input().split())
a1=a[:N]
#print a1

heapify(a1)

l1=[]
sum_a1=sum(a1)
l1.append(sum_a1)

# Max
for i in range(N,2*N):
	if a[i]>a1[0]:
		sum_a1=sum_a1+a[i]-a1[0]
		heappop(a1)
		heappush(a1, a[i])

	l1.append(sum_a1)

l2=[]
a2=[ -x for x in a[2*N:]]
heapify(a2)
sum_a2=-1*sum(a2)
l2.append(sum_a2)

# Min
for i in reversed(range(N,2*N)):
	if a[i]<-1*a2[0]:
		sum_a2=sum_a2+a[i]-(-1*a2[0])
		heappop(a2)
		heappush(a2,-1*a[i])
	l2.append(sum_a2)

ans=[]
for i in range(N+1):
	heappush(ans, -1*(l1[i]-l2[N-i]))

print ans[0]*-1


N = int(input())
array=[int(n) for n in input().split()]
lst=[]
for i in range(N):
    a =len(array)//2 -1
    l=array[:a+1]
    r= array[a+1:]
    if max(r)-array[a] > array[a]- min(l) > 0 or max(r)-array[a] > 0 > array[a]- min(l):
        r.pop(r.index(max(r)))
        array= l+r
    elif  array[a]- min(l) >max(r)-array[a] > 0 or  array[a]- min(l) > 0 > max(r)-array[a]:
        l.pop(l.index(min(l)))
        array= l+r
    else:
        array.remove(array[a])
print(sum(array[:N])-sum(array[N:]))


# https://atcoder.jp/contests/abc053/tasks/abc053_b
s = input()
a_index = s.find("A")
z_index = s.rfind("Z")
print(z_index - a_index + 1)

Score : 200 points

Problem Statement

Snuke has decided to construct a string that starts with A and ends with Z, by taking out a substring of a string s (that is, a consecutive part of s).

Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with A and ends with Z.

Constraints

1 ≦ |s| ≦ 200{,}000

s consists of uppercase English letters.

There exists a substring of s that starts with A and ends with Z.

Input

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

s

Output

Print the answer.

Sample Input 1

QWERTYASDFZXCV

Sample Output 1

5

By taking out the seventh through eleventh characters, it is possible to construct ASDFZ, which starts with A and ends with Z.

Sample Input 2

ZABCZ

Sample Output 2

4

Sample Input 3

HASFJGHOGAKZZFEGA

Sample Output 3

12


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

# input
s = input()

# solve
for f in range(len(s)):
    if s[i] == 'A':
        a = i
        break

for f in reversed(range(len(s))):
    if s[i] == 'Z':
        z = i
        break

# output
print(z - a + 1)


s = input()
print(s.rfind("Z")-s.find("A"))


s = input()
start = 0
end = 0
flag1 = True
flag2 = True
for i in range(len(s)):
    if s[i] == "A" and flag1 == True:
        start = i
        flag1 = False
    elif s[i] == "Z" and start != 0 and flag2 == True:
        end = i
        flag2 = False
slNnm = (end + 1) - start
print(slNnm)


from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]

def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W

def ceil(a, b):
    return (a + b - 1) // b

def main():
    s = input()
    print(s.rfind("Z") - s.find("A") + 1)

if __name__ == '__main__':
    main()


S = input()

a = 0
b = 0
for i in range(len(S)):
  if(S[i] == "A"):
    a = i
    break

for i in range(len(S))[::-1]:
    if(S[i] == "Z"):
      b = i
      break

print(b - a + 1)


s = input()
print(s.rfind("Z") - s.find("A") + 1)


K,S=map(int,input().split())
ans=0
for i in range(K+1):
    for j in range(K+1):
        k=S-i-j
        if 0<=k and k<=K:
            ans+=1
print(ans)

Score : 200 points

Problem Statement

You are given two integers K and S.

Three variable X, Y and Z takes integer values satisfying 0≤X,Y,Z≤K.

How many different assignments of values to X, Y and Z are there such that X + Y + Z = S?

Constraints

2≤K≤2500

0≤S≤3K

K and S are integers.

Input

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

K S

Output

Print the number of the triples of X, Y and Z that satisfy the condition.

Sample Input 1

2 2

Sample Output 1

6

There are six triples of X, Y and Z that satisfy the condition:

X = 0, Y = 0, Z = 2

X = 0, Y = 2, Z = 0

X = 2, Y = 0, Z = 0

X = 0, Y = 1, Z = 1

X = 1, Y = 0, Z = 1

X = 1, Y = 1, Z = 0

Sample Input 2

5 15

Sample Output 2

1

The maximum value of X + Y + Z is 15, achieved by one triple of X, Y and Z.


import math
#-------------
K, S = map(int, input().split())
#-------------
cnt = 0

for X in range(K+1):
  for Y in range(K+1):
    for Z in range(K+1):
      if S-(X+Y+Z) == 0:
        cnt += 1
print(cnt)


k,s = map(int,input().split())
ans = 0
for x in range(k+1):
    for y in range(k+1):
        z = s-(x+y)
        if 0 <= z and z<=k:
            ans += 1
print(ans)


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

cnt = 0
for l in range(k+1):
  for m in range(k+1):
    for n in range(k+1):
      if (l + m + n == s):
        cnt += 1
print(cnt)


K, S = map(int, input().split())

counter = 0

for i in range(K+1):
    x = i
    for ii in range(K+1):
        y = ii
        z = K - i - ii
        if 0<=z and z<=K and (x+y+z)==S:
            counter += 1

print(counter)


k,s=(int(x) for x in input().split())
ans=0
for i in range(k+1):
  for ii in range(k+1):
    if 0<=s-i-ii<=k:
        ans+=1
print(ans)


k,s = map(int,input().split())
ans = 0

for x in range(k+1):
  for y in range(k+1):
    z = s - x - y
    if z <= k and z >= 0:
      ans += 1

print(ans)


K, S = map(int, input().split())
ans = 0

for x in range(K+1):
    for y in range(K+1):
        if  0 <= S-x-y <= K:
            ans += 1
print(ans)


#https://atcoder.jp/contests/abc051/tasks/abc051_b
K, S = map(int, input().split(' '))

cnt = 0
for x in range(K+1):
    for y in range(K+1):
        for z in range(K+1):
            if x + y + z == S:
                cnt += 1
print(cnt)


k,s=map(int,input().split())
print(sum([h+i+j==s for j in range(k+1) for i in range(k+1) for h in range(k+1)]))


# ABC051 B - Sum of Three Integers
K,S = map(int,input().split())
ans = 0
for i in range(0,K+1):
    for j in range(0,K+1):
        k = S-i-j
        if 0<=k<=K:
                ans += 1
print(ans)


K, S = map(int, input().split())

count = 0

for i in range(K+1):
    x = i
    for j in range(min(K+1,S-x+1)):
        y = j
        z = S-x-y
        if x + y + z == S and z <= K:
            count += 1

print(count)


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

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

matched = []

for x in range(0, k + 1):
    for y in range(0, k + 1):
        z = s - x - y
        if 0 <= z and z <= 5:
            matched.append((x, y, z))

# print(matched)
print(len(matched))


k,s = map(int, input().split())
ans = 0

for x in range(k+1):
    for y in range(k+1):
        for z in range(k+1):
            if x + y + z == s:
                ans += 1
print(ans)


K,S = map(int, input().split())
cnt = 0
K += 1
for X in range(K):
    if X > S:
        break
    for Y in range(K):
        if X + Y > S:
            break
        for Z in range(K):
            if X + Y + Z == S:
                cnt += 1
            if X + Y + Z > S:
                break

print(cnt)


# coding: utf-8
K,S=[int(i) for i in input().split()]
ans=0
for x in range(K+1):
     for y in range(S-x+1):
        if S-x-y<=K:
             ans+=1
print(ans)


k,s=map(int,input().split())
cnt=0
for x in range(k+1):
    for y in range(k+1):
        for z in range(k+1):
            if x+y+z == s:
                cnt+=1
print(cnt)


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

ret = 0
for x in range(k + 1):
    for y in range(k + 1):
        for z in range(k + 1):
            if x + y + z == s:
                ret += 1
print(ret)


a = input().split()
k = int(a[0])
s = int(a[1])
count = 0
for n1 in range(k+1):
    for n2 in range(k+1):
        if 0<=(s - n1 - n2)<=k:
            count += 1

print(count)


#ARC051B

k,s=map(int,raw_input().split())
cnt=0
for x in xrange(k+1):
 for y in xrange(k+1):
  z=s-x-y
  if z>=0 and z<=k:
   cnt+=1
print cnt


def solve():
    S = input()[::-1]
    i = 0
    while i < len(S):
        if S[i:i+5] in ['maerd', 'esare']:
            i += 5
        elif S[i:i+6] == 'resare':
            i += 6
        elif S[i:i+7] == 'remaerd':
            i += 7
        else:
            return 'NO'
    return 'YES'

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

Score : 300 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:

Append one of the following at the end of T: dream, dreamer, erase and eraser.

Constraints

1≦|S|≦10^5

S consists of lowercase English letters.

Input

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

S

Output

If it is possible to obtain S = T, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of T in this order, to obtain S = T.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of T in this order, to obtain S = T.

Sample Input 3

dreamerer

Sample Output 3

NO


S = input()
S = S[::-1]
candidacies = ["dream", "dreamer", "erase", "eraser"]
candidacies = [c[::-1] for c in candidacies]

fi_flg = False
while fi_flg is False:
  if S[:6] in candidacies:
    S = S[6:]
  elif S[:5] in candidacies:
    S = S[5:]
  elif S[:7] in candidacies:
    S = S[:7]
  else:
    fi_flg = True

if len(S) == 0:
  print("YES")
else:
  print("NO")


S=input()
while 1:
    l=len(S)
    if S[-7:]   =="dreamer":
        S=S[0:l-7]
    elif S[-5:] =="dream":
        S=S[0:l-5]
    elif S[-6:] =="eraser":
        S=S[0:l-6]
    elif S[-5:] =="erase":
        S=S[0:l-5]
    else:break
if S=="":
    print("YES")
else:
    print("NO")


def main():
    target = input()
    string = ["eraser", "dreamer", "erase", "dream"]
    for i in range(len(target)):
        for s in string:
            if target[-len(s):] == s:
                target = target[:-len(s)]
        if target == "":
            break
    print("YES" if target == "" else "NO")

if __name__ == '__main__':
    main()


def slove():
    import sys
    input = sys.stdin.readline
    s = str(input().rstrip('\n'))
    s = s.replace("eraser", "").replace("erase", "").replace("dreamer", "").replace("dream", "")
    print("YES" if s == "" else "NO")

if __name__ == '__main__':
    slove()


#!/usr/bin/env python3
import sys
sys.setrecursionlimit(300000)

YES = "YES"  # type: str
NO = "NO"  # type: str

def solve(S: str):
    elms = ['dream', 'dreamer', 'erase', 'eraser']
    while S:
        found = False
        for e in elms:
            if S[-len(e):] == e:
                found = True
                S = S[:-len(e)]
                break
        if not found:
            print(NO)
            return
    print(YES)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == '__main__':
    main()


s = input()

while len(s) > 0:
    if s.startswith("dreamera"):
        s = s[5:]
        #print(s)
    elif s.startswith("eraser"):
        s = s[6:]
        #print(s)
    elif s.startswith("dreamer"):
        s = s[7:]
    elif s.startswith("dream"):
        s = s[5:]
    elif s.startswith("erase"):
      	s = s[5:]
    else:
        #print(s)
        print("NO")
        exit()
print("YES")


import sys

def main():
    S = input()

    S = S.replace('eraser', '').replace('erase', '').replace('dreamer', '').replace('dream', '')
    print('YES' if len(S)==0 else 'NO')

if __name__ == '__main__':
    main()


s = input()
words_r = ['eraser', 'erase', 'dreamer', 'dream']
for word_r in words_r:
    s = s.replace(word_r, '')
    #コードの意味:
    #s.replace(p,q) :文字列sにpという文字があればそれを先頭から順にqに置換していく
    #sはwords_rに含まれる文字列を''に置換した文字列になる
    #->条件に合うならｓは最終的に''に,そうでないならそれ以外になる
if (len(s) > 0):
    print('NO')
else:
    print('YES')


s=input()

s=s[::-1]

X=['maerd','remaerd','esare','resare']
ans='Yes'
i=0
while i<=len(s)-5:
    if s[i:i+5] in X:
        i+=5
    else:
        if s[i:i+6] in X:
            i+=6
        else:
            if s[i:i+7]  in X:
                i+=7
            else:
                ans='No'
                break

print(ans)


s = input()
judge = "YES"

s = s.replace("eraser", "")
s = s.replace("erase", "")
s = s.replace("dreamer", "")
s = s.replace("dream", "")

if s:
  judge = "NO"

print(judge)


s=input()
a=0
for i in range(1,n):
    if s[i]!=s[i-1]:
        a+=1
print(a)

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

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

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


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

S_list = [input() for x in range(N)]

sorted_S_list = sorted(S_list)

result = str()
for s in sorted_S_list:
  result = result + s

print(result)

Score : 200 points

Problem Statement

Iroha has a sequence of N strings S_1, S_2, ..., S_N. The length of each string is L.

She will concatenate all of the strings in some order, to produce a long string.

Among all strings that she can produce in this way, find the lexicographically smallest one.

Here, a string s=s_1s_2s_3...s_n is lexicographically smaller than another string t=t_1t_2t_3...t_m if and only if one of the following holds:

There exists an index i(1≦i≦min(n,m)), such that s_j = t_j for all indices j(1≦j<i), and s_i<t_i.

s_i = t_i for all integers i(1≦i≦min(n,m)), and n<m.

Constraints

1 ≦ N, L ≦ 100

For each i, the length of S_i equals L.

For each i, S_i consists of lowercase letters.

Input

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

N L
S_1
S_2
:
S_N

Output

Print the lexicographically smallest string that Iroha can produce.

Sample Input 1

3 3
dxx
axx
cxx

Sample Output 1

axxcxxdxx

The following order should be used: axx, cxx, dxx.


N, L = map(int, input().split())
Li = []
for i in range(N):
    s = input()
    Li.append(s)
Ls = sorted(Li)
S = ''.join(Ls)
print(S)


import math

line = input()
n, l = [int(x) for x in line.split()]
strings = []
for i in range (n):
	strings.append(input())
strings.sort()
seperator = ''
print(seperator.join(strings))


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

words = list()
for i in range(N):
  words.append(input())

words.sort()

print(*words,sep ="")


n, l = map(int, input().split())
A = [input() for _ in range(n)]
A.sort()
print("".join(A))


n,l = map(int,input().split())
s = [input() for i in range(n)]
s.sort()
ans = ""
for i in s:
    ans += i
print(ans)