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

pos = []
neg = []
zero = []

A.sort()

A2 = [A[i]**2 for i in range(N)]
A2.sort()
for i in range(N):
    if A[i] > 0:
        pos.append(A[i])
    elif A[i] == 0:
        zero.append(A[i])
    else:
        neg.append(A[i])

import bisect

#条件に合うものを重複して数えて後から重複しない組み合わせに変換
def fun(x):
    count = 0
    #xが0より大きいとき、後ろにある0は何個あるか
    if x >= 0:
        count += len(zero)*N
    #xを正で割ったとき、Aの中に何個それより大きいものがあるか
    for i in range(len(pos)):
        count += bisect.bisect_right(A,x//pos[i])
    #xを負で割ったとき、Aの中に何個それより小さいものがあるか(符合が逆転)
    #x+1にする(同じ数字がAにあるから)
    for i in range(len(neg)):
        count += N - bisect.bisect_right(A,(x+1)//neg[i])
    #条件に合う同じ要素を選ぶものを除く
    count -= bisect.bisect_right(A2,x)
    #半分にすれば重複しない組み合わせになる
    return count//2

left = -10**18
right = 10**18

#二分探索する
while right - left > 1:
    mid = (left+right)//2

    if fun(mid) >= K:
        right = mid
    else:
        left = mid

print(right)


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

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

def hasbelow1(x,b,j):
    if b==0:
        ret = 0 if x<=0 else len(a)-j
    elif b>0:
        mn = j-1
        mx = len(a)
        while mx>mn+1:
            mid = (mx+mn)//2
            if b*a[mid]<x:
                mn = mid
            else:
                mx = mid
        ret = mx-j
    else:
        mn = j-1
        mx = len(a)
        while mx>mn+1:
            mid = (mx+mn)//2
            if b*a[mid]<x:
                mx = mid
            else:
                mn = mid
        ret = len(a)-mx
    #if b!=0:
    #    ddprint("x {} b {} j {} mn {} mx {} ret {}".format(x,b,j,mn,mx,ret))
    return ret

def hasbelow(x,m):
    #ddprint("hasb x {} m {}".format(x,m))
    sm = 0
    for i in range(n-1):
        h = hasbelow1(x,a[i],i+1)
        #ddprint("i {} ai {} h {}".format(i,a[i],h))
        sm += h
        if sm>=m:
            return True
    return False

n,k = inm()
a = inl()
a.sort()
mx = 10**20
mn = -mx
while mx>mn+1:
    mid = (mx+mn)//2
    if hasbelow(mid,k):
        mx = mid
    else:
        mn = mid
    #ddprint("mx {} mn {}".format(mx,mn))
print(mn)

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

Score: 400 points

Problem Statement

We have N integers A_1, A_2, ..., A_N.

There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?

Constraints

All values in input are integers.

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

1 \leq K \leq \frac{N(N-1)}{2}

-10^9 \leq A_i \leq 10^9\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \dots A_N

Output

Print the answer.

Sample Input 1

4 3
3 3 -4 -2

Sample Output 1

-6

There are six ways to form a pair. The products of those pairs are 9, -12, -6, -12, -6, 8.

Sorting those numbers in ascending order, we have -12, -12, -6, -6, 8, 9. The third number in this list is -6.

Sample Input 2

10 40
5 4 3 2 -1 0 0 0 0 0

Sample Output 2

6

Sample Input 3

30 413
-170202098 -268409015 537203564 983211703 21608710 -443999067 -937727165 -97596546 -372334013 398994917 -972141167 798607104 -949068442 -959948616 37909651 0 886627544 -20098238 0 -948955241 0 -214720580 277222296 -18897162 834475626 0 -425610555 110117526 663621752 0

Sample Output 3

448283280358331064

Submitted source-code file size, in bytes.

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

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


n, k = map(int, input().split())
a = list(map(int, input().split()))
po = []
ng = []
zr = 0
for i in range(n):
  if a[i]>0:
    po.append(a[i])
  elif a[i]<0:
    ng.append(a[i])
  elif a[i]==0:
    zr += 1
lp=len(po)
ln=len(ng)
negn=lp*ln
zern=zr*(n-zr)+zr*(zr-1)//2

if k <= negn:
  p=[0]*negn
  c=0
  for i in range(lp):
    for j in range(ln):
      p[c]=po[i]*ng[j]
      c+=1
  p.sort()
  print(p[k-1])
elif negn < k <= negn+zern:
  print(0)
else:
  p=[0]*(n*(n-1)//2-negn-zern)
  c=0
  for i in range(lp-1):
    for j in range(i+1, lp):
      p[c]=po[i]*po[j]
      c+=1
  for i in range(ln-1):
    for j in range(i+1, ln):
      p[c]=ng[i]*ng[j]
      c+=1
  p.sort()
  print(p[k-1-negn-zern])


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

import os
import datetime

def main():
    a, b = map(int, input().split())
    val = list(map(lambda x: int(x), input().split()))

    result_dict = []

    for i in range(len(val)):
        for j in range(i+1, len(val)):
            result_dict.append(val[i] * val[j])

    min_list = sorted(result_dict)
    print(min_list[b-1])

if __name__ == '__main__':
    main()


import itertools

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

multis = []
max_value = 0
for combination in itertools.combinations(A, 2):
    if len(multis) <= K:
        multis.append(combination[0] * combination[1])
    else:
        m = combination[0] * combination[1]
        if m < max_value:
            multis.append(m)
            max_value = max(max_value, m)

result = sorted(multis)[K - 1]
print(result)


import itertools
def resolve_d():
    n, k = map(int, input().split())
    l = map(int, input().split())
    c = itertools.combinations(l, 2)
    results = []
    for combi in c:
        results.append(combi[0] * combi[1])
    results = sorted(results)
    print(results[k-1])
resolve_d()


a,b=map(int,input().split());print(a*b if a<=9 and b<=9 else -1)

Score : 100 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation.

Given are two integers A and B.

If Takahashi can calculate A \times B, print the result; if he cannot, print -1 instead.

Constraints

1 \leq A \leq 20

1 \leq B \leq 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If Takahashi can calculate A \times B, print the result; if he cannot, print -1.

Sample Input 1

2 5

Sample Output 1

10

2 \times 5 = 10.

Sample Input 2

5 10

Sample Output 2

-1

5\times 10 = 50, but Takahashi cannot do this calculation, so print -1 instead.

Sample Input 3

9 9

Sample Output 3

81


A, B = map(int,input().split())
if A <10 and B<10:
    print(A*B)
else :
    print(-1)


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

if a>9 or b>9:
  print(-1)
else:
  print(a*b)


a,b=map(int,input().split())
if a<10 and b<10:
  print(a*b)
else:
  print('-1')


a, b=map(int,input().split())
print(a*b if 1<=a<=9 and 1<=b<=9 else '-1')


a=int(input())

b=int(input())

if(0<=a<=9 & 0<=b<=9):
    print(a*b)

else:
    print(-1)


A,B = map(int,input().split())
if 1<=A<=9 and 1<=B<=9:
  print(A*B)
else:
  print('-1')


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

if a > 9 or b > 9:
    print(-1)
else:
    print(a * b)


a, b = list(map(int, input().split()))
if (1 <= a <= 9 and 1 <= b <= 9):
  print(a * b)
else:
  print(-1)


aaa,baa=map(int, input().split())
caa=aaa*baa
if baa>10 or aaa>10:
  print('-1')
else:
  print(caa)


a,b = int(input())

if a<=9 or b<=9:
    print(a*b)
else:
    print(-1)


a, b = map(int, input().split())
ans = a*b if a<=9 ans b<=9 else -1
print(ans)


a,b=input().split()
a=int(a)
b=int(b)
if ((a>9) | (b>9)):
  print(-1)
else:
	print(a*b)


a,b=map(int,input().split())
print(a*b if a<10 and b<10 else -1)


S = list(input())
flag = False
if S[0] == S[1]:
    flag = True
N = len(S)
K = int(input())
cnt = 0

for i in range(N-1):
    if S[i] == S[i+1]:
        cnt += 1
        S[i+1] = '!'

if S[N-1] == S[0]:
    if flag:
        print(cnt*K)
    else:
        print(cnt*K+(K-1))
else:
    print(cnt*K)

Score : 300 points

Problem Statement

Given is a string S. Let T be the concatenation of K copies of S.
We can repeatedly perform the following operation: choose a character in T and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different.

Constraints

1 \leq |S| \leq 100

S consists of lowercase English letters.

1 \leq K \leq 10^9

K is an integer.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

T is issiiissii. For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997


s=list(input())
k=int(input())
l=[]
p=1
for i in range(len(s)-1):

    if s[i]==s[i+1]:
        p+=1
    else:
        l.append(p)
        p=1
l.append(p)
m=0
if len(l)==1:
    print(l[0]*k//2)

else:
    if s[len(s)-1]==s[0]:
        for i in range(1,len(l)-1):
            m+=l[i]//2
        m*=k
        m+=(k-1)*(l[0]+l[len(l)-1])//2
        m+=l[0]//2+l[len(l)-1]//2
        print(m)

    else:
        for i in range(len(l)):
            m+=l[i]//2
        m*=k
        print(m)


# coding: utf-8
S = input()
K = int(input())
l = [0]
tmp = 0
for i in range(len(S)-1):
    if S[i] == S[i+1]:
        # l.append(tmp + 1)
        tmp += 1
    else:
        if tmp > 0:
            l.append(tmp+1)
        tmp = 0
if tmp != 0:
    l.append(tmp+1)
ans = 0
ans += l[-1]//2
if S[0] == S[-1]:
    l[-1] += 1
for i in range(1, len(l)-1):
    ans += l[i]//2 * K
# print(ans)
ans += l[-1]//2 * (K-1)
# print(l)
print(ans)


s=input()#与えれる文字列
n=int(input())#文字列sを繰り返す回数
l=len(s)
c=0
for i in range(l):
  if s[i-1] == s[i]:
    c+=1
    i+=1
if s[0]==s[-1]:
  if s[-1]==s[-2]:
    c-=1

print(int(c)*n)


S=list(input())
K=int(input())
S2 = S*2
tmp=0
tmp2=0
for i in range(1,len(S)):
    if S[i-1]==S[i]:
        S[i]="0"
        tmp += 1

for i in range(1,len(S2)):
    if S2[i-1]==S2[i]:
        S2[i]="0"
        tmp2 += 1
print(tmp+(tmp2-tmp)*(K-1))


s = input()
k = int(input())
t = ''
i = 0
count = 0
first = 0
end =  0
while s[0] ==s[i]:
	first += 1
	i = i + 1

i = len(s)-1
while s[i] ==s[len(s)-1]:
	end += 1
	i = i - 1

i =0
while i < len(s)-2:
	if s[i] == s[i+1]:
		if i == len(s)-2:
			count +=1
			i += 1
		if s[i+1] == s[i+2]:
			count += 1
			i += 2
		else:
			count += 1
			i += 1
	else:
		i += 1

if i == len(s)-2:
	if s[i] == s[i+1]:
		count +=1
	if s[0] == s[len(s)-1]:
		if (first + end) %2 !=0
			count += 1
print(count*k)


S, K = open(0).read().split()
# print(S, K)
# print(alpha)
# print(type(S))
list_s = list(S)
# print(list_s)
cnt = 0
for i in range(len(list_s)-1):
    if list_s[i] == list_s[i+1]:
        list_s[i+1] = "_"
        cnt += 1
#     print(list_s)
# print(cnt)
# print(list_s)
print(cnt * int(K))


def main():
    S = input()
    K = int(input())
    ans = 0

    if len(S) is 1:
        print(K // 2)
        return

    if len(set(S)) is 1:
        print(len(S) * K // 2)
        return

    i = 0
    while i < len(S) - 1:
        if S[i] is S[i + 1]:
            ans += 1
            i += 1
        i += 1

    if ans is 0 and S[0] is S[-1]:
        print(K - 1)
    else:
        print(ans * K)

if __name__ == "__main__":
    main()


S = input()
K = int(input())
N = len(S)
cnt = 0
flg1 = False
flg2 = False
flg3 = False
flg4 = False
for i in range(N-1):
    if S[i] != S[i+1]:
        flg3 = True
        break
if (flg3 == False) and N % 2 == 1:
    print((N*K)//2)
    exit()
if (S[0] == S[N-1]) and K != 1:
    cnt += 1
    flg1 = True
if S[N-2] == S[N-1]:
    flg4 = True
for i in range(N-1):
    if flg2:
        flg2 = False
        continue
    if (i == N - 2) and flg1:
        break
    if S[i] == S[i+1]:
        cnt += 1
        flg2 = True
# print(cnt)
if flg1 and flg4 == False:
    print(cnt*K-1)
else:
    print(cnt*K)
# print(cnt*K)


# coding: utf-8
from decimal import *
S = input()
K = Decimal(input())
if len(S) == 1:#文字列の長さが1のときは話が変わる
    ans = K // 2
    print(ans)
    exit()
fletter = 0 # 最初の文字の連続数を数える
lletter = 0 # 最後の文字の連続数を数える
cletter = 0 # 現在連続している文字の連続数を数える
cng = 0 # 文字変更の必要がある文字をカウント
for i in range(len(S)): # 最初の文字の連続数を数える
    if S[0] == S[i]:
        fletter += 1
    else:
        break
for i in range(len(S)):
    if S[-1] == S[-(i + 1)]:
        lletter += 1
    else:
        break
for i in range(len(S) - 1): # 1文字ずつ連続しているかを判定
    if S[i] == S[i + 1]:
        cletter += 1
    else:
        cng -= - cletter // 2
        cletter = 0
cng -= - cletter // 2 # 最終文字まで到達したら文字変更数の処理
if S[0] == S[-1] and fletter % 2 == 1 and lletter % 2 == 1:
    ans = Decimal((cng + 1) * K - 1)
else:
    ans = Decimal(cng * K)
print(ans) #解答の出力


#import sys

#input = sys.stdin.readline

#import heapq
#import math
#import fractions

#def sosuhante(n):
#    for k in range(2, int(math.sqrt(n))+1):
#        if n% k ==0:
#            return False
#    return True

def main():
#    h,w,a,b = map(int, input().split())
    s = input()
    k= int(input())
    a= []
    b= []
    n=len(s)
    for i in range(n):
        a.append(s[i])
        b.append(s[i])

    a[0]="a"
    if n > 1:
        for i in range(1,n):
            if b[i]==b[i-1]:
                a[i]="a" if a[i-1]=="a" else "b"
            else:
                a[i]="b" if a[i-1]=="a" else "a"
#    print(a)
    temp=1
    henka=0
    if n > 1:
        for i in range(1,n):
            if a[i]==a[i-1]:
                temp+=1
                if i==n-1:
                    henka+=temp//2
                    temp=1
            else:
                henka+=temp//2
                temp=1
    temp=1
    hasi=0
    mae=1
    usiro=1
    if k > 1 and n > 1 and b[0]==b[n-1]:
        for i in range(1,n):
            if a[i]==a[i-1]:
                temp+=1
                if i==n-1:
                    mae=temp
            else:
                mae=temp
                break
        temp=1
        for i in range(n-2,-1,-1):
            if a[i]==a[i+1]:
                temp+=1
                if i==0:
                    usiro=temp
            else:
                usiro=temp
                break
        if (mae+usiro)//2 > mae//2 + usiro//2:
            hasi=1
#    print(henka,"henka")
    count=0
    if k > 1 and n>1:
        count=henka*k + hasi*(k-1)
    if k == 1 and n>1:
        count=henka
    if n==1 and k==1:
        count=0
    if n==1 and k>1:
        count=k//2
    if mae==usiro and mae==n:
        count=(n*k)//2

    print(count)

if __name__ == "__main__":
    main()


S=list(input())
S+=S
K=int(input())
ans=0
i=0
while i<len(S)-1:
    if S[i+1]==S[i]:
        ans+=K
        i+=1
    i+=1
print(ans//2)


s=input()
k=int(input())
n=len(s)
if n==1:
    print(k//2)
    exit()
if n==2:
    if s[0]==s[1]:
        print(k)
    else:
        print(0)
    exit()
tc=1
ac=0
p=s[0]
for i in range(1,n):
    if s[i]==p:
        tc+=1
    else:
        ac+=tc//2
        tc=1
        p=s[i]
else:
    ac+=tc//2
ans=ac*k
if s[0]==s[-1]:
    if s[0]!=s[1] and s[-1]!=s[-2]:
        ans+=k//2
print(ans)


import sys
input = sys.stdin.readline

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

for i in range(M):
    a = A.index(max(A))
    A[a] = int(A[a]/2)

print(sum(A))

Score : 400 points

Problem Statement

Takahashi is going to buy N items one by one.

The price of the i-th item he buys is A_i yen (the currency of Japan).

He has M discount tickets, and he can use any number of them when buying an item.

If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for 9 yen, as follows:

Buy the 1-st item for 2 yen without tickets.

Buy the 2-nd item for 3 yen with 2 tickets.

Buy the 3-rd item for 4 yen with 1 ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced 1000000000 yen for 0 yen with 100000 tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000


import heapq

n, m = map(int, input().split())
A = list(map(lambda x: -int(x), input().split()))

heapq.heapify(A)
for i in range(m):
    item = heapq.heappop(A)
    heapq.heappush(A, (-1) * (-item // 2))

print(-sum(A))


import heapq

N,M = map(int,input().split())
Price_List = list(map(lambda x:x*(-1),map(int,input().split())))
heapq.heapify(Price_List)
for i in range(M):
    val = heapq.heappop(Price_List)* -1 // 2 * -1
    heapq.heappush(Price_List,val)
print(-sum(Price_List))


#!/usr/bin/env python3
import heapq
# import bisect

n, m = list(map(int, input().split()))
a = list(map(lambda x: int(x)*(-1), input().split()))

heapq.heapify(a)
for i in range(m):
    value = heapq.heappop(a)
    value = (value+1)//2
    heapq.heappush(a, value)

# print(a)
print(-sum(a))


import sys
import heapq

input = sys.stdin.readline

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

A = list(map(lambda x: x * (-1), A))
heapq.heapify(A)

for _ in range(M):
    mx = heapq.heappop(A)
    heapq.heappush(A, mx // 2 if mx % 2 == 0 else mx // 2 + 1)

print(sum(A) * (-1))


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

for i in range(M):
    A.sort(reverse=True)
    A[0] = A[0] // 2

x = sum(A)
print(x)


import heapq
N,M =map(int,input().split())
A=[-int(x) for x in input().split()]#大きい順で扱う為にマイナスを付ける

heapq.heapify(A)#Aを優先度付キューへ変換

for i in range(M):
  saitakane = heapq.heappop(A)#最高値を取り出す
  heapq.heappush(A,-(-saitakane//2))#切り捨ての為に正の数にしてから半分にして戻す（追加）
print(-sum(A))


import heapq
n, m = map(int, input().split())
a = [int(i) * (-1) for i in input().split()]
heapq.heapify(a)
for i in range(m):
    x = heapq.heappop(a) * (-1) // 2
    heapq.heappush(a, x * (-1))
print(-sum(a))


# -*- coding: utf-8 -*-
"""
Created on Thu Oct  3 07:43:37 2019

@author: avina
"""

import heapq

class Maxheap():

    def __init__(self, x):
        self.heap = [-e for e in x]
        heapq.heapify(self.heap)

    def push(self, value):
        heapq.heappush(self.heap, -value)

    def pop(self):
        return -heapq.heappop(self.heap)

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

l = list(map(int, input().split()))
a = Maxheap(l)
for i in range(l):
    b = a.pop()//2
    a.push(b)

sums = 0
for i in range(n):
    sums += a.pop()
print(sums)


# -*-coding: utf-8 -*-
import heapq
def main():
    N, M = map(int, input().split())
    A = list(map(lambda x: int(x)*(-1), input().split()))
    heapq.heapify(A)

    for _ in range(M):
        tmp_min = heapq.heappop(A)
        heapq.heappush(A, (-1)*(-tmp_min//2))

    print(-sum(A))
if __name__ == '__main__':
    main()


import sys
import numpy as np
import math
def input():
    return sys.stdin.readline()[:-1]

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

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

for _ in range(M):
    A[np.argmax(A)] = math.floor(max(A) / 2)

print(sum(A))


import sys
from bisect import insort_left
input = sys.stdin.readline

def main():
    n, m = map(int, input().split())
    a = [int(i) for i in input().split()]
    a.sort()
    for _ in range(m):
        b = a.pop()//2
        insort_left(a, b)
    print(sum(a))

main()


import heapq

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

for i in range(N):
    heapq.heappush(hq, A[i]*(-1))

for i in range(M):
    tmp = heapq.heappop(hq) // 2
    heapq.heappush(hq, tmp)

print(sum(hq)*(-1))


from heapq import heapify, heappush, heappop

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

Q = [-int(x) for x in input().split()]
heapify(Q)

for i in range(M):
    a = -heappop(Q)
    heappush(Q, -(a//2))

ans = 0
for i in range(N):
    ans += -heappop(Q)

print(ans)


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

for i in range(M):
    a_max = max(A)
    max_index = A.index(a_max)
    A[max_index] = a_max / 2

print(sum(A))


import sys

A = [int(x) for x in input().split()]
#print(AB)
N = A[0]
M = A[1]
#print(N)
#print(M)
B = [int(x) for x in input().split()]
B.sort()
for i in range(M):
    B[-1] = int (B[-1] /2)
    B.sort()
print(B)

# for i in range(M):
#     max_index = B.index(max(B))
#     B[max_index] = int(B[max_index] / 2)
#     if sum(B) == 0:
#         print(0)
#         sys.exit()
    #print(B)
print(sum(B))


n,m = map(int,input().split())
a = list(map(int,input().split()))
for i in range(m):
    b = a.pop(a.index(max(a))) // 2
    a.append(b)
print(sum(a))


n,m=map(int, input().split())
a=sorted(map(int, input().split()),reverse=True)

a[0]//=2
for i in range(1,m):
    a[a.index(max(a[:i]))] //=2
print(sum(a))


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

for i in range(n):
    a = sorted(a)
    a[-1] = int(a[-1]/2)
print(sum(a))


import math
import heapq

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

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

tmp = 0

for i in range(m):

        tmp = heapq.nlargest(1,a)
        a.remove(tmp[0])
        a.append(math.floor(tmp[0]/2))

print(sum(a))


import numpy as np
N, M = list(map(int, input().split(' ')))
x = np.array(list(map(int, input().split(' '))))
for m in range(M):
    if np.sum(x) == 0:
        break
    x = np.sort(x)[::-1]
    x[0] = np.trunc(x[0]/2.0)
print(np.sum(x))


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

A = sorted(A)[::-1]

waribiki = 0
index = 0

if len(A)==1:
    print(A[0]//pow(2,M))
    exit()

while waribiki < M:
    if index < N and A[index]>2 and A[index+1]>2:
        x = A[index] // A[index+1]
        if x+waribiki>M: x = M-waribiki
    else: x = 1

    if A[index] > 2:
        A[index] = A[index]//pow(2, x)
        waribiki+=x

    index += 1
    if index==N: index=0

print(sum(A))


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

A.sort()

for i in range(M):
    A.sort(reverse = True)
    A[0] = A[0] // 2

print(sum(A))


data = input()
l = data.split()
l = list(map(int, l))
N, M = l[0], l[1]

s = input()
prices = s.split()
prices = list(map(int, prices))

#prices.sort(reverse = True)
#print(prices)

for i in range(M): #　半額券の数だけループ
    prices.sort(reverse = True)
    prices[0] = int(prices[0] / 2)

print(sum(prices))


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

for _ in range(M):
  A[-1] = int(A[-1]/2)
  A.sort()
print(sum(A))


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

for i in range(m):
  s = a.index(max(a))
  a[s] = int(a[s] / 2)

print(sum(a))


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

for i in range(m):
    a=sorted(a)
    a[-1]/=2

ans=0

for i in range(n):
    ans+=int(a[i])
print(ans)


import heapq
import math

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

negA = list(map(lambda x: -x, A))

heapq.heapify(negA)

for _ in range(M):
    nedan = -heapq.heappop(negA)
    nedan = nedan // 2
    heapq.heappush(negA, -nedan)

print(-sum(negA))


#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify

import itertools
import math, fractions
import sys, copy

def L(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline().rstrip())
def SL(): return list(sys.stdin.readline().rstrip())
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI1(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return [list(x) for x in sys.stdin.readline().split()]
def R(n): return [sys.stdin.readline().strip() for _ in range(n)]
def LR(n): return [L() for _ in range(n)]
def IR(n): return [I() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def LIR1(n): return [LI1() for _ in range(n)]
def SR(n): return [SL() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]

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

def make_list(n, *args, default=0): return [make_list(*args, default=default) for _ in range(n)] if len(args) > 0 else [default for _ in range(n)]

dire = [[1, 0], [0, 1], [-1, 0], [0, -1]]
dire8 = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]
alphabets = "abcdefghijklmnopqrstuvwxyz"
ALPHABETS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
MOD = 1000000007
INF = float("inf")

sys.setrecursionlimit(1000000)

class RollingHash:
    def __init__(self, seq, f=ord):
        self.n = len(seq)
        self.base1, self.base2 = 1007, 2009
        self.mod1, self.mod2 = 1000000007, 1000000009
        self.f = f # set numerizing function

        self.hash1, self.hash2 = [0]*(self.n+1), [0]*(self.n+1)
        self.power1, self.power2 = [1]*(self.n+1), [1]*(self.n+1)

        for i, e in enumerate(seq):
            self.hash1[i+1] = (self.hash1[i] * self.base1 + self.f(e)) % self.mod1
            self.hash2[i+1] = (self.hash2[i] * self.base2 + self.f(e)) % self.mod2
            self.power1[i+1] = (self.power1[i] * self.base1) % self.mod1
            self.power2[i+1] = (self.power2[i] * self.base2) % self.mod2

    # get hash value of seq[left:right]
    def get(self, l, r):
        v1 = (self.hash1[r] - self.hash1[l] * self.power1[r-l]) % self.mod1
        v2 = (self.hash2[r] - self.hash2[l] * self.power2[r-l]) % self.mod2
        return v1, v2

    # get lcp of seq[a:] and seq[b:]
    def getLCP(self, a, b):
        l = self.n - max(a, b) + 1
        left, right = 0, l
        while right - left > 1:
            mid = (left + right) // 2
            if self.get(a, a+mid) == self.get(b, b+mid): left = mid
            else: right = mid
        return left

def main():
    N = I()
    S = SL()

    rh = RollingHash(S)
    ans = 0

    def check(m):
        d = defaultdict(int)
        for i in range(N-m+1):
            v = rh.get(i, i+m)
            if d[v]:
                if i >= d[v] + m:
                    return True
            else: d[v] = i
        return False

    left, right = 0, N//2+1
    while right - left > 1:
        mid = (left + right) // 2
        if check(mid): left = mid
        else: right = mid

    print(left)

if __name__ == '__main__':
    main()

Score : 500 points

Problem Statement

Given is a string S of length N.

Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping.

More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following:

l_1 + len \leq l_2

S[l_1+i] = S[l_2+i] (i = 0, 1, ..., len - 1)

If there is no such integer len, print 0.

Constraints

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

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. If there is no such non-empty string, print 0 instead.

Sample Input 1

5
ababa

Sample Output 1

2

The strings satisfying the conditions are: a, b, ab, and ba. The maximum length among them is 2, which is the answer.
Note that aba occurs twice in S as contiguous substrings, but there is no pair of integers l_1 and l_2 mentioned in the statement such that l_1 + len \leq l_2.

Sample Input 2

2
xy

Sample Output 2

0

No non-empty string satisfies the conditions.

Sample Input 3

13
strangeorange

Sample Output 3

5


N = int(input())
S = input()
l = 0
k = 1
for i in range(N - 1):
   while True:
       if S[i : i + k] in S[i + k :]:
           k += 1
       else:
           break
   l = max(l, k - 1)
print(l)


def Z_algo(S):
    n = len(S)
    LCP = [0]*n
    i = 1
    j = 0
    c = 0#最も末尾側までLCPを求めたインデックス
    for i in range(1, n):
        #i番目からのLCPが以前計算したcからのLCPに含まれている場合
        if i+LCP[i-c] < c+LCP[c]:
            LCP[i] = LCP[i-c]
        else:
            j = max(0, c+LCP[c]-i)
            while i+j < n and S[j] == S[i+j]: j+=1
            LCP[i] = j
            c = i
    LCP[0] = n
    return LCP

ans = 0
N = int(input())
S = input()
for i in range(N):
    LCP = Z_algo(S[i:])
    for j, l in enumerate(LCP):
        tmp = min(l, j)
        ans = max(ans, tmp)
print(ans)


import sys
n = int(sys.stdin.readline())
S = sys.stdin.readline().rstrip()
f = False
for l in range(n//2, 0, -1):
    for j in range(n):
        ptn = S[j:j+l]
        if j+l ==n:
            break
        #print(ptn)
        if ptn in S[j+l:]:
            print(l)
            f = True
            break
    if f == True:
        break
else:
    print(0)


#! /usr/bin/env python3

### @file wsap.py
### @brief
### @author Yusuke Matsunaga (松永 裕介)
###
### Copyright (C) 2019 Yusuke Matsunaga
### All rights reserved.

def Z_algorithm(S) :
    n = len(S)
    A = [ 0 for i in range(n) ]
    A[0] = n
    i = 1
    j = 0
    max_val = 0
    while i < n :
        while (i + j) < n and S[j] == S[i + j] :
            j += 1
        A[i] = j
        if j <= i and max_val < j :
            max_val = j
        if j == 0 :
            i += 1
            continue
        k = 1
        while (i + k) < n and k + A[k] < j :
            A[i + k] = A[k]
            k += 1
        i += k
        j -= k

    return max_val

def wsap(S) :
    n = len(S)
    max_len = 0
    for i in range(n) :
        val = Z_algorithm(S[i:])
        if max_len < val :
            max_len = val
    return max_len

if __name__ == '__main__' :

    n = int(input())
    S = input()
    max_len = wsap(S)
    print(max_len)


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

def check(l):
    if l == 0:
        return True
    for i in range(n-l*2 + 1):
        cnt = 0
        k = 0
        for j in range(i+l, n):
            if s[i+k] == s[j]:
                k += 1
                cnt += 1
            else:
                if j > n-l:
                    break

                j -= k
                k = 0
                cnt = 0

            if cnt == l:
                # print(l, i, j, cnt,)
                return True

    return False

lb = 0
ub = n // 2 + 1
while ub - lb > 1:
    mid = (ub + lb) // 2
    if check(mid):
        lb = mid
    else:
        ub = mid

print(lb)


N = int(input())
S = list(input())
ba = ord("a")
for i in range(N):
  S[i] = ord(S[i]) - ba + 1
B = 27
mod = 10 ** 11 + 7
def contain(a, b):
  al = len(a)
  bl = len(b)
  #print(al, a)
  if al > bl: return False
  t = pow(B, al)
  ah = 0; bh = 0
  for i in range(al):
    ah = ah * B + a[i]
    bh = bh * B + b[i]
  for i in range(bl - al + 1):
    if ah == bh: return True
    if i + al < bl:
      #print(i, i + al)
      bh = bh * B + b[i + al] - b[i] * t
  return False
res = 0
for i in range(N):
  r = min(i + N // 2, N + 1)
  l = i + res + 1
  m = (l + r) // 2
  if l > r: continue
  while r - l > 3:
    m = (l + r) // 2
    if contain(S[i: m], S[m: ]):
      l = m
      res = max(res, m - i)
    else:
      r = m
  if m <= N:
    if contain(S[i: m + 1], S[m + 1: ]):
      res = max(res, m + 1 - i)
  if m + 1 <= N:
    if contain(S[i: m + 2], S[m + 2: ]):
      res = max(res, m + 2 - i)
  if m + 2 <= N:
    if contain(S[i: m + 3], S[m + 3: ]):
      res = max(res, m + 3 - i)
print(res)


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

m = 0
for i in range(int(n / 2) + 1):
    for j in range(i + 1, n + 1):
        if s[j:].find(s[i:j]) > -1:
            m = max(m, len(s[i:j]))
print(m)


import sys,collections as cl,bisect as bs,heapq as hq
sys.setrecursionlimit(100000)
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def search(a,n):
    se = dict()
    data = []
    for i in range(0,len(a)-n+1):
        kkk = a[i:i+n]
        kkk = "".join(kkk)
        if In(kkk,data):
            for j in range(len(se[kkk])):
                if se[kkk][j] <= i-n:
                    return True
            else:
                se[kkk].append(i)
        else:
            bs.insort(data,kkk)
            se[kkk] = [i]
    return False
def solver():
    n = onem()

    s = list(input())
    l = 0
    r = n//2
    for i in range(n):
        mid = -(-(l+r)//2)
        ans = search(s,mid)
        if l == mid:
            break
        if ans:
            l = mid
        else:
            r = mid-1
    print(l)

solver()


a = int(input())
s = input()

if a >= 3200:
    print(s)
else:
    print("red")

Score : 100 points

Problem Statement

You will be given an integer a and a string s consisting of lowercase English letters as input.

Write a program that prints s if a is not less than 3200 and prints red if a is less than 3200.

Constraints

2800 \leq a < 5000

s is a string of length between 1 and 10 (inclusive).

Each character of s is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

a
s

Output

If a is not less than 3200, print s; if a is less than 3200, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

a = 3200 is not less than 3200, so we print s = pink.

Sample Input 2

3199
pink

Sample Output 2

red

a = 3199 is less than 3200, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

a = 4049 is not less than 3200, so we print s = red.


a = int(input())
input_s = input()

if 3200 <= a:
    output_s = ("pink")
elif a <3200:
    output_s = ("red")

print(output_s)


a = int(input())
s = input()

if a >= 3200 :
    print(s)
else:
    print('red')


# from collections import Counter
# n = int(input())
# li = list(map(int, input().split()))
# a, b = map(int, input().split())
a = int(input())
s = input()
print("red" if a < 3200 else s)


a=int(input())
s=input()
if a>=3200:
  print(s)
else:
  print("red")


a=int(input())
s=input()

if a<3200 :
  s='red'

print(s)


a = int(input())
s = str(input())
if a < 3200:
  print(s)
else:
  print("red")


n=int(input())
string_list=[input() for i in range(n)]
a = int(string_list[0])
if a <= 3200:
  print("red")
else:
  print(a[1])


def main():
  a = int(input())
  s = input()
  ans = s if a >=3200 else 'red'
  print(ans)

if __name__ == '__main__':
  main()


a = int(input())
s = input()

print('red' if a < 3200 else s)


a  = int(input())
s = input()

if a >= 3200:
    print(s)
else:
    print('red')


a = int(input())
s = input()
if a >= 3200:
  print(s)
else:
  print('red')


f=lambda:map(int,input().split())
n,q=f()
a=[[]for _ in range(n+1)]
for _ in range(n-1):
    i,j=f()
    a[i]+=[j]
b=[0]*(n+1)
for _ in range(q):
    i,j=sorted(f())
    b[i]+=j
for i in range(n):
    for j in a[i]:
        b[j]+=b[i]
print(*b[1:])

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20


# 初期入力 readlineだけで1950ms⇒1234ms
#                           PyPy   ⇒867ms
from collections import defaultdict
from collections import deque
import sys
input = sys.stdin.readline
N,Q = (int(x) for x in input().split())

connection ={i:set() for i in range(1,N+1)}
for i in range(1,N):
    a,b = (int(i) for i in input().split())
    connection[a].add(b)
    connection[b].add(a)
nord_point = defaultdict(lambda: 0)
for i in range(1,Q+1):
    a,b = (int(i) for i in input().split())
    nord_point[a] +=b

#BSF

dq =deque()
start =1
dq.append(start)
passed =set()
counter_dic ={i:0 for i in range(1,N+1)}
counter_dic[start] =nord_point[start]
while len(dq) >0:
    now =dq.popleft()
    passed.add(now)
    for next in connection[now]:
        if next not in passed:
            #頂点のカウンター＝親のカウンター ＋ 頂点のポイント
            counter_dic[next] =counter_dic[now] +nord_point[next]
            dq.append(next)
#出力
print(*counter_dic.values())


n,q = map(int,input().split())
parent = [[] for i in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    parent[a].append(b)

ans = [0] * n

for i in range(q):
    p,x = map(int,input().split())
    p -= 1
    ans[p] += x

a = ''
for i, son in enumerate(parent):
    a += str(ans[i]) + ' '
    for j, s in enumerate(son):
        ans[s] += ans[i]
print(a)


n, q = map(int, input().split())
g = [ [] for _ in range(n) ]
for _ in range(n-1):
    a, b = map(int, input().split())
    g[a-1].append(b-1)
    g[b-1].append(a-1)

pl = [0] * n
for _ in range(q):
    p, x = map(int, input().split())
    pl[p-1] = x

def dfs(curr, pare):
    for chi in g[curr]:
        if chi == pare: continue
        pl[chi] += pl[curr]
        dfs(chi, curr)

def main():
    dfs(0,-1)
    print(pl)

if __name__ == "__main__":
    main()


#138-d
from collections import deque

def bfs(edges, u, p, cost):
    #cost:今までのコスト
    #root0から順に、costsを更新してゆく
    cost += costs[u]
    costs[u] = cost
    nodes = edges[u]
    for v in nodes:
        if v!=p:
            bfs(edges, v, u, cost)

n,q = [int(i) for i in input().split()]
costs=[0]*n

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

for _ in range(n-1):
    a,b = [int(i) for i in input().split()]
    edges[a-1].append(b-1)
    edges[b-1].append(a-1)

for _ in range(q):
    u,value = [int(i) for i in input().split()]
    costs[u-1] += value

bfs(edges, 0, -1, 0)
print(*costs)


import collections
def LI(): return list(map(int,input().split()))
N,Q = LI()
ab = [LI() for _ in range(N-1)]
px = [LI() for _ in range(Q)]
ans = [0]*(N+1) #1_index
graph = {i:collections.deque() for i in range(1,N+1)} #1_index
for a,b in ab:
        graph[a].append(b)
        graph[b].append(a)
for p,x in px:
    ans[p] += x
seen = [-1]*(N+1) #1_index
stack = []
def dfs():
    seen[1] = 1
    stack.append(1)
    while stack:
        s = stack.pop()
        if not graph[s]:
            continue
        for g_NO in graph:
            if seen[g_NO]!=-1:
                continue
            seen[g_NO] = 1
            stack.append(g_NO)
            ans[g_NO] += ans[s]
dfs()
print(*ans[1:])


from collections import deque
N,Q=map(int,input().split())
nondirtree=[[] for _ in range(N)]
dirtree=[[] for _ in range(N)]
for i in range(N-1):
    a,b=map(int,input().split())
    nondirtree[a-1].append(b-1)
    nondirtree[b - 1].append(a - 1)
points=[list(map(int,input().split())) for _ in range(Q)]
#print(points)
v=0
d=deque()
d.append(v)
seen=[0]*N
seen[0]=1
score=[0]*N
ans=[0]*N
while len(d)!=0:
    v=d.popleft()
    for j in nondirtree[v]:
        if seen[j]==0:
            dirtree[v].append(j)
            seen[j]=1
            d.append(j)
    #print(d,seen,dirtree)
    #input(
#print(dirtree)
for i in range(Q):
    score[points[i][0]-1]=score[points[i][0]-1]+points[i][1]
#print(score)
v=0
d=deque()
d.append(v)
ans[0]=score[0]
while len(d)!=0:
    v=d.popleft()
    for j in dirtree[v]:
        ans[j]=ans[v]+score[j]
        d.append(j)
    #input()
    #print(ans)
print(*ans,sep=" ")


import sys
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**6)
n,q=map(int,input().split())
g=[[] for i in range(n)]
for _ in range(n-1):
    a,b=map(int,input().split())
    g[a-1].append(b-1)
    g[b-1].append(a-1)
add=[0]*n
for _ in range(q):
    a,b=map(int,input().split())
    add[a-1]+=b
st=set() ; v=0 ; s=add[0]
ans=[0]*n
def dfs(g,v,s):
    global ans,st
    if v not in st:
        st.add(v)
        ans[v]+=s
    else: return
    for p in g[v]:
        dfs(g,p,s+add[p])
dfs(g,v,s)
print(*ans)


from collections import deque

def solve():
    N, Q = map(int, input().split())
    ab = [[0, 0] for _ in range(N-1)]
    for i in range(N-1):
        ab[i] = list(map(int, input().split()))
    px = [[0, 0] for _ in range(Q)]
    for i in range(Q):
        px[i] = list(map(int, input().split()))

    graph = [[] for _ in range(N+1)]
    for a, b in ab:
        graph[a].append(b)
        graph[b].append(a)

    val = [0 for _ in range(N+1)]
    for p, x in px:
        val[p] += x

    que = deque([1])
    parent = [0 for _ in range(N+1)]
    while que:
        i = que.popleft()
        for j in graph[i]:
            if j == parent[i]:
                continue
            parent[j] = i
            que.append(j)
            val[j] += val[i]

    print(*val[1:])

if __name__ == '__main__':
    solve()


import sys
sys.setrecursionlimit(1000000)
n,q=map(int,input().split())
G=[[]*n for i in range(n)]
P=[0]*n
V=[0]*n
for i in range(n-1):
	a,b=map(int,input().split())
	G[a-1].append(b-1)
	G[b-1].append(a-1)
for i in range(q):
	c,d=map(int,input().split())
	P[c-1]+=d
def dsf(i,p):
	V[i]=1
	P[i]+=p
	p=0
	for j in G[i]:
		if V[j]!=1:
			dsf(j,P[i])
dsf(0,0)
print(' '.join(map(str,P)))


#D
from collections import deque
n,q=map(int,input().split())
data=[[] for i in range(n+1)]
counter=deque([0 for i in range(n+1)])
for i in range(n-1):
    a,b=map(int,input().split())
    data[a].append(b)
    data[b].append(a)
for i in range(q):
    p,x=map(int,input().split())
    counter[p]+=x
h=deque([1])
while h:
    a=h.popleft()
    for i in range(len(data[a])):
        counter[data[a][i]]+=counter[a]
        h.append(data[a][i])
        data[data[a][i]].remove(a)
counter.popleft()
print(*counter)


n, q = list(map(int, input().split(' ')))
inf = [[] for _ in range(n+1)]
p_list = [0 for _ in range(n+1)]

for i in range(n-1):
    a, b = list(map(int, input().split(' ')))
    inf[a].append(b)

def add_p(num, point):
    if len(inf[num]) == 0:
        p_list[num] += point
        return 0
    p_list[num] += point
    for next_num in inf[num]:
        print(next_num, point)
        add_p(next_num, point)
    return 0
for i in range(q):
    p, x = list(map(int, input().split(' ')))
    add_p(p, x)
result = p_list[1:]
result = list(map(str, result))
print(' '.join(result))


import sys
sys.setrecursionlimit(100000)

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

class Node:
    def __init__(self):
        self.children = []
        self.point = 0

    def get_children(self):
        if not self.children:
            return [self]
        ret = [self]
        for child in self.children:
            c = child.get_children()
            ret.extend(c)
        return ret

nodes = [Node() for i in range(n)]
for i in range(n-1):
    a, b = map(int, input().split(' '))
    nodes[a-1].children.append(nodes[b-1])

queries = []
for i in range(q):
    p, x = map(int, input().split(' '))
    queries.append((p, x))

for query in queries:
    ps = nodes[query[0]-1].get_children()
    for p in ps:
        p.point += query[1]

print(*[str(n.point) for n in nodes])


import math
import sys
import numpy as np
from collections import defaultdict, deque, Counter
from itertools import accumulate, product, permutations,combinations, combinations_with_replacement
from operator import itemgetter
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd

max_value = 1000000000
min_value = -1000000000
sys.setrecursionlimit(max_value)

n,q = map(int,input().split())
edges = []
for i in range(n-1):
	edges.append(list(map(int,input().split())))
for i in range(len(edges)):
	edges[i][0] -= 1
	edges[i][1] -= 1

operations = []
for i in range(q):
	operations.append(list(map(int,input().split())))
for i,e in enumerate(operations):
	operations[i][0] -= 1

leafs = [[] for i in range(n)]

for edge in edges:
	leafs[edge[0]].append(edge[1])

values = [0 for i in range(n)]

def dfs(pos):
	reward_edges.append(pos)
	if len(leafs[pos]) == 0:
		pass
	else:
		for e in leafs[pos]:
			dfs(e)

for operation in operations:
	reward_edges = []
	dfs(operation[0])
	for reward_edge in set(reward_edges):
		values[reward_edge] += operation[1]
ans = ''
for e in values:
	ans += str(e) + ' '
print(ans[:-1])


def dfs(v,p):
    for i in tree[v]:
        if i==p:
            continue
        res[i]+=res[v]
        dfs(i,v)

n,q = map(int, input().split())
tree = [[] for _ in range(n)]
for i in range(n-1):
    a,b = map(int,input().split())
    tree[a-1].append(b-1)
    tree[b-1].append(a-1)

res = [0]*n
for i in range(q):
    p,x = map(int,input().split())
    res[p-1] += x

dfs(0,0)
print(*res)


from collections import deque
N, Q = map(int, input().split())
count = [0 for i in range(N)]
graph = {i:[] for i in range(N)}

for i in range(N-1):
  a, b = map(int, input().split())
  graph[a-1]+=[b-1]
  graph[b-1]+=[a-1]

for i in range(Q):
  p, x = map(int, input().split())
  count[p-1] += x

q = deque([0])
log = [True]*N
log[0]=False
while q:
  v = q.popleft()
  ls = graph[v]
  for l in ls:
    if log[l]:
      q.append(l)
      log[l]=False
      count[l] += count[v]
ans = [str(i) for i in count]
print(' '.join(ans))


from sys import stdin
n, q = map(int,input().split())
ab = []
px = []

"""
for i in range(n-1):
	ab+=[list(map(int,input().split()))]
"""

ab=[list(map(int,input().split())) for i in range(n-1)]

px=[list(map(int,input().split())) for i in range(q)]
edge = [-1]*(n)

for a,b in ab:
	edge[b-1] = a-1

c = [0]*n

for p,x in px:
	c[p-1] += x

for i in range(n-1):
	c[i+1] += c[edge[i+1]]

for i in range(n):
	print(c[i])


import sys
re = sys.stdin.readline
N, Q = map(int, re().split())
graph = [[] for _ in range(N)]
for i in range(N - 1):
    a, b = map(int, re().split())
    graph[a - 1].append(b - 1)
    graph[b - 1].append(a - 1)
items = [0] * N
for i in range(Q):
    q, x = map(int, input().split())
    items[q - 1] += x

p = [-1] * N
import sys

sys.setrecursionlimit(10 ** 9)

ans = [0] * N

def dfs2(tar,pre, plus):
    ans[tar] += plus + items[tar]
    for v in graph[tar]:
        if v == pre:
            continue
        dfs2(v, tar, ans[tar])

dfs2(0,-1, 0)

for a in ans:
    print(a, end=" ")


n,q=map(int,input().split())
ls=[0]*(n+1)

ki_list=[list(map(int,input().split())) for i in range(n-1)]
ki_list.sort()

for i in range(q):
    p,x = map(int,input().split())
    ls[p]+=x

for i in ki_list:
    oya,ko=i[0],i[1]
    ls[ko]+=ls[oya]

del ls[0]
print(*ls)


N,Q = map(int,input().split(" "))
A = []

B = [0 for j in range(N)]
for i in range(N-1):
    tmp = list(map(int,input().split(" ")))
    A.append(tmp)
A.sort()
for j in range(Q):
    tmp = list(map(int,input().split(" ")))
    B[tmp[0]-1] += tmp[1]

for i in range(N-1):
        B[A[i][1]-1] += B[A[i][0]-1]

for i in range(N):
        print(B[i],end=" ")


N, Q = map(int, input().split())
G = [tuple(map(int, input().split())) for _ in range(N-1)]
W = [tuple(map(int, input().split())) for _ in range(Q)]

# 親に付いている重み
r = [0,] * (N+1)
for p, x in W:
    r[p] += x

# 木の隣接関係 (a<bは保証されている)
for a, b in G:
    r[b] += r[a]

print(*r[1:])


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

T = dict()
V = np.zeros(N+1)

a, b = map(int, input().split())
T[a] = []
T[a].append(b)

for i in range(N-2):
	a, b = map(int, input().split())
	if T.get(a) == None:
		T[a] = []
	T[a].append(b)

def change(a, v):
	V[a] += v
	temp = T.get(a)
	if(temp==None):
		return
	else:
		for x in temp:
			change(x, v)

for i in range(Q):
	a, v = map(int, input().split())
	change(a, v)

print(' '.join([str(int(x)) for x in V[1:]]))


N, Q = list(map(int,input().rstrip().split(' ')))
sum = [0]*N
connected = list()
from functools import lru_cache

for _ in range(N-1):
    connected.append(list(map(int,input().rstrip().split(' '))))

@lru_cache(maxsize=1000)
def subtree(node):
    sub_tree_list = []
    for c in connected:
        if c[0] == node:
            sub_tree_list.append(c[1])

    if sub_tree_list == []:
        return [node]
    else:
        tmp = []
        for sub in sub_tree_list:
            tmp += subtree(sub)
        return [node] + tmp

for _ in range(Q):
    p, x = list(map(int,input().rstrip().split(' ')))
    sub = subtree(p)
    for y in sub:
        print(sum)
        print("y is :" + str(y))
        sum[y-1] += x

for r in sum:
    print(r, end=' ')


N, Q = map(int, input().split())
pa = [list(map(int, input().split())) for _ in range(N-1)]
glp = list(range(N + 1))

for i in range(N-1):
    if glp[pa[i][0]] > glp[pa[i][1]]:
        glp[pa[i][0]] = glp[pa[i][1]]
    else:
        glp[pa[i][1]] = glp[pa[i][0]]

tree = [[]for i in range(N + 1)]
counter = [0]*N
for a, b in pa:
    if glp[a] != a:
        tree[glp[a]].append(b)
        tree[a].append(b)
    else:
        tree[a].append(b)

for i in range(Q):
    p, x = map(int, input().split())
    for pi in tree[p]:
        counter[pi-1] += x
    counter[p-1] += x

print(" ".join(map(str, counter)))


import sys,heapq,math,resource
from collections import deque,defaultdict
printn = lambda x: sys.stdout.write(x)
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
DBG = True # and False
R = 10**9 + 7

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

def setrlim():
  sys.setrecursionlimit(250000)
  soft,hard = resource.getrlimit(RLIMIT_STACK)
  # setrlimit works on ubuntu (and atcoder), but not on WSL
  resource.setrlimit(RLIMIT_STACK, (128*1024*1024,hard))

def dfs(i,fromup):
    y[i] = fromup + v[i]
    for d in dst[i]:
        dfs(d,y[i])

n,q = inm()
dst = [ [] for i in range(n) ]
for i in range(n-1):
    a,b = inm()
    a -= 1
    b -= 1
    dst[a].append(b)
v = [0]*n
for i in range(q):
    p,x = inm()
    p -= 1
    v[p] += x
y = [0]*n
dfs(0,0)
for i in range(n):
    printn((' ' if i>0 else '') + str(y[i]))
print("")


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

edges = []
toE = [[] for _ in range(N)]
frE = [[] for _ in range(N)]
for _ in range(M):
    fr, to, c = map(int, input().split())
    fr -= 1
    to -= 1
    edges.append((fr, to, -(c - P)))
    toE[fr].append(to)
    frE[to].append(fr)

def getVisitedList(s, edges):
    visited = [False] * N
    st = [s]
    visited[s] = True
    while st:
        now = st.pop()
        for to in edges[now]:
            if not visited[to]:
                visited[to] = True
                st.append(to)
    return visited

canGo = getVisitedList(0, toE)
canBack = getVisitedList(N - 1, frE)

def sol():
    minDist = [10**18] * N
    minDist[0] = 0
    for i in range(N + 1):
        for fr, to, c in edges:
            d = minDist[fr] + c
            if minDist[to] > d:
                if i == N and canGo[fr] and canBack[to]:
                    return -1
                minDist[to] = d
    return max(0, -minDist[N - 1])

print(sol())

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

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

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


import sys
sys.setrecursionlimit(10000000)

f_inf = sys.maxsize

N, M, P = map(int, input().split())
ABC_d = {}
for m in range(M):
    A, B, C = map(int, input().split())
    if A in ABC_d:
        ABC_d[A].append([B, C - P])
    else:
        ABC_d[A] = [[B, C - P]]

cost = [-f_inf] * N
cost[0] = 0

max_num_sum = N * (N + 1) // 2

def solve(pos, cnt, num_sum):
    global cost
    global pass_cnt

    if not(pos in ABC_d): return
    if cnt > N or num_sum > max_num_sum:
        cost[pos-1] = f_inf;

    for B, C in ABC_d[pos]:
        num_sum += B
        if cost[B - 1] == f_inf or cost[B - 1] >= cost[pos - 1] + C:
            pass
        elif cost[pos-1] == f_inf:
            cost[B-1] = f_inf
            solve(B, cnt + 1, num_sum)
        elif cost[B - 1] < cost[pos - 1] + C:
            cost[B - 1] = cost[pos - 1] + C
            solve(B, cnt + 1, num_sum)

solve(1, 1, 1)

if (cost[-1] == sys.maxsize):
    print (-1)
else:
    print (max(0, int(cost[-1])))


inputs = [int(x) for x in input().split()]
n, m, p = inputs[0], inputs[1], inputs[2]
inputs = [[int(x) for x in input().split()] for _ in range(m)]
graphs, scores = {}, {}
for x, y, c in inputs:
  if y in graphs.keys():
    graphs[y].append([x, c - p])
  else:
    graphs[y] = [[x, c - p]]
    scores[y] = None
for k, v in graphs.items():
  graphs[k] = sorted(v, key=lambda x: x[0])

scores[1] = 0

for goal in range(2, n+1):
  for start, score in graphs[goal]:
    if scores[start] is None:
      continue
    total = scores[start] + score
    if (scores[goal] is None) or (total > scores[goal]):
      scores[goal] = total

print(scores[n] if scores[n] > 0 else 0)


from collections import deque
N, M, P = map(int, input().split())
G = [[] for i in range(N)]
RG = [[] for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    G[a-1].append((b-1, P-c))
    RG[b-1].append((a-1, P-c))

def chk(s, G):
    P = [0]*N
    que = deque([s])
    used = [0]*N
    used[s] = 1
    while que:
        v = que.popleft()
        P[v] = 1
        for w, c in G[v]:
            if used[w]:
                continue
            que.append(w)
            used[w] = 1
    return P
P0 = chk(0, G); P1 = chk(N-1, RG)
I = []
for i in range(N):
    if P0[i] == P1[i] == 1:
        I.append(i)

dist = [10**18]*N
dist[0] = 0
L = len(I)
for i in range(L+1):
    update = 0
    for v in I:
        d = dist[v]
        for w, c in G[v]:
            if d + c < dist[w]:
                dist[w] = d + c
                update = 1
    if not update:
        break
else:
    print("-1")
    exit(0)

print(max(-dist[N-1], 0))


#!/usr/bin/env python3
import sys

inf = float('inf')

def solve(N: int, M: int, P: int, a: "List[int]", b: "List[int]", c: "List[int]"):
    V = list(range(N))

    next_v = [[] for v in V]
    for i in range(M):
        next_v[a[i]-1].append((b[i]-1, c[i]))

    D = [-inf for v in V]
    D[0] = 0

    prev = [None for v in V]

    positive = [False for v in V]

    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    prev[v] = u
    ans = D[N-1]

    for i in range(N-1):
        for u in V:
            for v, w in next_v[u]:
                alt = D[u] + w
                if alt > D[v]:
                    D[v] = alt
                    positive[v] = True
                if positive[u]:
                    positive[v] = True

    if positive[N-1]:
        print(-1)
    else:
        print(max(0, ans))
    return

# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    A = [int()] * (M)  # type: "List[int]"
    B = [int()] * (M)  # type: "List[int]"
    C = [int()] * (M)  # type: "List[int]"
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = (int(next(tokens))-P)
    solve(N, M, P, A, B, C)

if __name__ == '__main__':
    main()


n = int(input())
h = list(map(int,input().split()))
for i in range(1,n):
    if h[i] > h[i-1]:
        h[i] -= 1
    else:
        pass
l = list(h)
l.sort()
if h == l:
    print('Yes')
else:
    print('No')

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


N=int(input())
H=list(map(int,input().split()))
if N>1:
    for i in range(N-1):
        if H[i]<=H[i+1]-1:
            H[i+1]-=1
        if H[i]>H[i+1]:
            print('No')
            exit()
    print('Yes')
else:
    print('Yes')


N = int(input())
A = list(map(int,input().split()))
pre = -999
frag = 0

for i in range(N+1):
    if A[i]-1 >= pre:
        pre = A[i] - 1
    elif A[i] >= pre:
        pre = A[i]
    else:
        frag += 1
        break

if frag == 1:
    print("No")
else:
    print("Yes")


n = int(input())
h = [int(x) for x in input().split()]

flag = True

for i in range(0,n-1):
    if h[i] > h[i+1]:
        h[i] -= 1

for i in range(1,n):
    if h[i-1] > h[i]:
        flag = False
        break

if flag:
    print("Yes")
else:
    print("No")


n=int(input())
h=list(map(int,input().split()))
maxim=h[-1]
h=h[::-1]
for i in range(n-1):
    if h[i]-maxim>=2:
        print('NO')
        exit()

    elif h[i+1]-h[i]==1:
        h[i+1]+=-1

    elif h[i]-maxim==1:
        h[i]+=-1
    elif h[i+1]-h[i]>=2:
        print('NO')
        exit()

print('YES')


n=int(input())
h=list(map(int,input().split()))
ans='Yes'
h_max=h[0]
for i in range(1,n):
  if h_max+1>h[i]:
    break
#    print(h_max,h[i],ans)
  elif h_max+1==h[i]:
    h_max=h[i]
#    print(h_max,h[i],ans)
  else:
    ans='No'
#    print(ans)
print(ans)


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

if ans==0:
    print("Yes")
else:
    print("No")


n = int(input())
h = list(map(int, input().split()))
if n == 1:
    print('Yes')
else:
    i = 0
    f = 0
    while i < n-1:
        if h[i]-h[i+1] > 1:
            print('No')
            i = n
        elif h[i]-h[i+1] == 1:
            f += 1
            if f == 2:
                print('No')
                i = n
            else:
                i += 1
        elif h[i] == h[i+1]:
            i += 1
        else:
            f = 0
            i += 1
    if i == n-1:
        print('Yes')


N = int(input())
H_list = [int(e) for e in input().split()]

judge='Yes'
num = H_list[0]
flag = False

for i in range(N-1):
  if H_list[i] > H_list[i+1]:
    if flag == True:
      judge = 'No'
      break;
    else:
      H_list[i] -= 1
      flag = True

  else:
    flag = False

print(judge)


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

for i in range(1, n):
  if h[i-1] == h[i]:
    continue
  elif h[i-1] == h[i] - 1:
    continue
  else:
    print('No')
    exit()

print('Yes')


N = int(input())
*H, = map(int, input().split())
current = 0
for h1, h2 in zip(H, H[1:]):
    diff = h1 - h2
    if diff > 1 or (diff == 1 and current == h1): print('No'); break;
    current = h2
else:
    print('Yes')


input()
r=list(map(int,input().split()))[::-1]

#print(r)

temp=r[0]
flag=0
for item in r:
  if temp>=item:
    temp=item
  elif temp>=item-1:
    temp=item-1
  else:
    flag=1
    break

print("Yes" if flag==0 else "No")


N = int(input())
H = []
H = input().split(" ")
for i in range(N):
    H[i] = int(H[i])

ochinchin = True
for i in range(1, N-1):
    if H[i]<H[i-1]:
        H[i-1] -= 1
        if H[i]<H[i-1]:
            ochinchin = False
            break
        elif i > 2:
            if H[i-1]<H[i-2]:
                ochinchin = False
                break

if ochinchin:
    print("Yes")
else:
    print("No")


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

hosei =0
for i in range(N-1,1,-1):
    H0=H[i]-H[i-1]
    if H0+hosei <= -2:
        print("No")
        exit()
    elif H0+hosei == -1:
        hosei = -1

print("Yes")


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

if n == 1:
    print("Yes")
    exit()
hs[0] -= 1
for i in range(n-1):
    if hs[i] > hs[i+1]:
        hs[i+1] -= 1

flag = True
for i in range(n-1):
    if hs[i] > hs[i+1]:
        flag = False
if flag:
    print("Yes")
else:
    print("No")


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

if n == 1:
    print("Yes")
    exit()
elif n == 2:
    if h[0] <= h[1]:
        print("Yes")
        exit()
    else:
        print("No")
        exit()

for i in range(1,n-1):
    if h[i] <= h[i+1] and h[i-1] <= h[i]:
        pass
    elif h[i] - h[i+1] == 1 and h[i] - h[i-1] >= 1:
        pass
    elif h[i-1] - h[i] == 1 and h[i+1] >= h[i]:
        pass
    else:
        print("No")
        exit()

print("Yes")


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

if N == 1:
    print("Yes")
    exit(0)

minused = False
for i in range(N - 1):
    left = H_list[i]
    right = H_list[i + 1]
    if right - left <= -2:
        print("No")
        exit(0)

    if minused:
        if right - left >= 0:
            continue
            minused = False
        else:
            print("No")
            exit(0)
    else:
        if right - left == -1:
            H_list[i] = H_list[i] - 1
            minused = True
print("Yes")


n=int(input())
H=list(map(int,input().split()))
d=0
for i in range(0,n-1):
    if H[n-i-1]-H[n-i-2]<-1:
        print("No")
        break
    elif H[n-i-1]-H[n-i-2]==-1:
        H[n - i - 2]=H[n-i-2]-1
        d=d+1
    else:
        d=d+1
if d==n-1:
    print("Yes")


from sys import stdin
import math
import fractions
from collections import deque
from collections import Counter
import itertools

INF = 10 ** 10

N = int(stdin.readline().rstrip())
H = [int(x) for x in stdin.readline().rstrip().split()]

flg = True

minn = -INF

for i in range(N-1):
    diff = H[i] - H[i+1]

    if diff <= 0:
        minn = H[i]
        continue

    if diff == 1:
        if H[i] - 1 < minn:
            flg = False
            break
        minn = H[i] - 1
    else:
        flg = False
        break

if flg:
    print("Yes")
else:
    print("No")


n=int(input())
h_list=list(map(int,input().split()))
for i in range(n-1):
    if h_list[i+1] == h_list[i]:
        continue
    elif h_list[i + 1] - h_list[i] > 0:
        h_list[i+1]=h_list[i+1]-1
    else:
        print('No')
        exit(0)
print(('Yes'))


l,r=map(int,input().split())

cnt=[]

for i in range(l,r+1):
  if i%2019!=0:
    for j in range(l,r+1):
      if j%2019>=0:
        a=(l*(l+1)%2019)
        cnt.append(a)
        break
      else:
        a=(j*(j-1)%2019)
        cnt.appnd(a)
        break
print(min(cnt))

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


import itertools

l, r = map(int, input().split())
l_rest = l % 2019
r_rest = r % 2019

if l_rest == 0 or r_rest == 0:
    print(0)
elif r-l < 2019:
    lr_list = list(range(l_rest, r_rest+1))
    lr_comb = list(itertools.combinations(lr_list, 2))
    min_rest = 2018
    for comb in lr_comb:
        rest = comb[0] * comb[1]
        min_rest = min(min_rest, rest%2019)
    print(min_rest)
elif r-l >= 2019:
    print(0)


import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline
ra = range
enu = enumerate

def read_ints():
    return list(map(int, read().split()))

def read_a_int():
    return int(read())

def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret

def read_col(H):
    '''
    H is number of rows
    A列、B列が与えられるようなとき
    ex1)A,B=read_col(H)    ex2) A,=read_col(H) #一列の場合
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return tuple(map(list, zip(*ret)))

def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため

MOD = 2019
INF = 2**31  # 2147483648 > 10**9
# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# https://atcoder.jp/contests/abc133/tasks/abc133_c
# i,jの2019倍は必ず2019で割り切れる
# i+2019a ≡ i (mod 2019)より iもjもそれぞれ2019で割った余りを採用すれば良い

L, R = read_ints()
L = L % MOD
R = R % MOD

if R <= L:
    R += MOD

ans = INF
for i, j in combinations(ra(L, R + 1), r=2):
    # print(i, j, i * j % MOD)
    ans = min(ans, i * j % MOD)
print(ans)


l,r=map(int,input().split())
if r-l>=2019:
    minimum=0
else:
    left,right=l%2019,r%2019
    minimum=2018**2
    for i in range(left,right+1):
        for j in range(i+1,right+1):
            minimum=min(minimum,i*j%2019)
print(minimum)


L,R = map(int,input().split())
if R-L >= 2019:
    print(0)
else:
    s = 2019
    for i in range(L,R):
        s = min(s, (i*(i+1)) % 2019)
    print(s%2019)


L, R=map(int, input().split())
mod=2019
A=[0]*(R-L+1)
for i in range(L, R+1):
  A[i]=i%mod

A=sorted(A)
print((A[0]*A[1])%mod)


#abc133 c
L,R=map(int,input().split())
x=R-L
ans=0
hidari=L%2019
migi=R%2019

if x>=2019:
    ans=0
else:
    ans=hidari*(hidari+1)
print(ans)


L,R=map(int,input().split())
ls=[]
LS=[]
if L-R>=672 or L==0:
  print(0)
else:
  ans=2019
  for i in range(L,R+1):
    for j in range(i+1,R+1):
      if i>=j:
        print(ans)
        exit()
      x=(i*j)%2019
      ans=min(x,ans)


L, R = map(int, input().split())
mini = mod = 2019

for i in range(L, R+1):
    for j in range(i+1, R+1):
        mod = (i * j) % 2019
        mini = min(mini, mod)

print(mini)


import numpy as np
l,r=map(int,input().split())
s=np.array(range(l,r+1))
ans=[2018]
for i in range(r-l):
    for j in range(i+1,r-l+1):
        ans=min((s[i]%2019)*(s[j]%2019),ans)
        if ans==0:
            break
print(ans)


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

l=L%2019
r=R%2019

ans=0

if R-L<2019 and l<r:
    D=[]
    for i in range(l,r):
        for j in range(i+1,r+1):
            D.append((i*j)%2019)

ans=min(D)

print(ans)


import sys
input = sys.stdin.readline
L,R = map(int, input().split())
ans = 10000
diff = 0
for i in range(L,R+1):
	if i % 2019 < ans:
		ans = i % 2019
	diff += 1
	if diff > 3000:
		break
print(ans*(ans+1))


def main():
    L, R = list(map(int, input().split()))
    ans = 2018
    end = min(R+1, L+2019))
    for i in range(L, end-1):
        for j in range(i+1, end):
            print(ans, (i*j)%2019)
            ans = min(ans, (i*j)%2019)
    print(ans)

main()


l, r = map(int, input().split())

mods = []
for i in range(l, r):
    for j in range(i + 1, r + 1):
        mods.append((i % 2019) * (j % 2019))

print(min(mods))


s=input()
t=''
i=0
while(i<len(s)):
    if i<len(s)-1 and s[i:i+2]=='BC':
        t+='D'
        i+=2
    else:
        t+=s[i]
        i+=1
t=t[::-1]
N=len(t)
i=0
ans=0
while(i<N):
    if t[i]=='D':
        j=i
        cnt=0
        while(j<N and t[j]!='B' and t[j]!='C'):
            if t[j]=='D':
                cnt+=1
            else:
                ans+=cnt
            j+=1
        i=j
    i+=1
print(ans)

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


s=input()
a=s.replace("BC","D")[::-1]
ans=0
i=0
while i<len(a):
  if a[i]=="D":
    k=1
    while True:
      try:
        if a[i+k]=="A" or a[i+k]=="D":
          ans+=1;k+=1
        else:
          i+=k-1
          break
      except:break
  i+=1
print(ans)


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

if __name__ == "__main__":
    s = input()
    ope_num = 0
    index = 0
    a_stock = 0
    b_stock = 0
    s = list(s)
    while index < len(s):
        si = s[index]
        # print(index)
        # print(si)
        # print(a_stock)
        # print(b_stock)
        # print(ope_num)
        # print()
        if si == "A":
            if b_stock > 0:
                b_stock = 0
                a_stock = 1
            else:
                a_stock = 1
        elif si == "B" and a_stock > 0 and b_stock == 0:
            b_stock = 1
        elif si == "C" and a_stock > 0 and b_stock > 0:
            ope_num = ope_num + 1
            s[index - 2] = "B"
            s[index - 1] = "C"
            s[index] = "A"
            a_stock = 0
            b_stock = 0
            if index - 4 >= -1:
                index = index - 4
            else:
                index = index - 1
        else:
            a_stock = 0
            b_stock = 0
        index = index + 1
    print(ope_num)

# ABCの数
# ABCの前にあるAの分だけ追加で操作できる
# ABCの後にある(BC)の分だけ追加で操作できる

# Aがあれば覚えておく
# ABCと来たら、それより前側に隣接しているAの回数だけ追加で操作できる
# 見つかったABCをBCAに置き換える
# BCAのAから走査を継続する


s=input()

i=0
c=0
flag=0
while True:
	if i>len(s)-3: break
	if s[i]=="A" and s[i+1]=="B" and s[i+2]=="C":
		s=s[:i]+"B"+s[i+1:]
		s=s[:i+1]+"C"+s[i+2:]
		s=s[:i+2]+"A"+s[i+3:]
		c+=1
		if i>0:
			i-=1
			flag+=1
		continue
	else:
		if flag:
			i+=2+flag
			flag=0
		else: i+=1

print(c)


h,w = map(int,input().split())
L = ["#" + input() + "#" for i in range(h)]
L = ["#"*(w+2)] + L + ["#"*(w+2)]
d = [["#"]+[0]*w + ["#"] for i in range(h)]
d = [["#"]*(w+2)] + d + [["#"]*(w+2)]
print(L,d)
li =((1,0),(0,1),(-1,0),(0,-1))

cnt = 0
while True:#not all(d[j][i] == "#" for j in range(1,h+1) for i in range(1,w+1)):
    for p in range(1,h):
        for q in range(1,w):
            if L[p][q] == "#":
                #print(p,q)
                d[p][q] = "#"
                #print(d)
                for x,y in li:
                    if L[p+x][q+y] == ".":
                        d[p+x][q+y] = "#"
    cnt +=1
    flag = False
    for j in range(1,h):
        for i in range(1,w):
            if d[j][i] == "#":
                flag = True
            else:
                flag = False
                break
    if flag == True:
        break
print(cnt)

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

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

Sample Output 2

3


from collections import deque

h, w = map(int, input().split())
a = [list(input()) for _ in range(h)]

cnt = [[10 ** 10] * w for _ in range(h)]
for i in range(h):
    for j in range(w):
        if a[i][j] == "#":
            cnt[i][j] = 0
def bfs(q, v, c):
    while q:
        y, x = q.pop()
        for i, j in ([0, 1], [1, 0], [-1, 0], [0, -1]):
            ny = y + i
            nx = x + j
            if 0 <= nx < w and 0 <= ny < h and v[ny][nx] == 0:
                v[ny][nx] = 1
                if c[ny][nx] >= c[y][x] + 1:
                    c[ny][nx] = c[y][x] + 1
                    q.append([ny, nx])

for i in range(h):
    for j in range(w):
        if a[i][j] == "#":
            queue = deque()
            queue.append([i, j])
            visited = [[0] * w for _ in range(h)]
            bfs(queue, visited, cnt)
            """
            for k in range(h):
                print(cnt[k])
            print()
            """
ans = 0
for i in range(h):
    ans = max(ans, max(cnt[i]))
print(ans)


import sys
from collections import deque

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

def main():
    H,W = map(int,input().split())
    A = [list(input()) for _ in range(H)]

    def bfs(x,y,A):
        que = deque()
        que.append((x,y))

        while que:
            x,y = que.popleft()

            for dx,dy in ((-1,0),(1,0),(0,-1),(0,1)):
                sx = x + dx
                sy = y + dy
                if sx < 0 or sx >= H or sy < 0 or sy >= W or A[sy][sx] == '#':
                    continue
                cnt = 1 if A[y][x] == '#' else A[y][x] + 1
                if A[sy][sx] == '.':
                    que.append((sx,sy))
                    A[sy][sx] = cnt
                elif A[sy][sx] > cnt:
                    que.append((sx,sy))
                    A[sy][sx] = cnt

    for x in range(W):
        for y in range(H):
            if A[y][x] == '#':
                bfs(x,y,A)
    ans = 0
    for a in A:
        a = [i if i != '#' else 0 for i in a]
        ans = max(ans,max(a))
    print(ans)

if __name__ == "__main__":
    main()


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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in read() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())

def main():

    H, W = in_nn()
    grid = in_map()

    ans = 0
    move = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while sum(grid) != 0:

        next_grid = copy.copy(grid)
        for y in range(H):
            for x in range(W):
                if not grid[x + y * W]:
                    continue
                for (px, py) in move:
                    nx, ny = x + px, y + py
                    if 0 <= nx < W and 0 <= ny < H:
                        if not grid[nx + ny * W]:
                            next_grid[x + y * W] = False
                            break
        ans += 1
        grid = next_grid

    # print(grid)
    print(ans)

if __name__ == '__main__':
    main()


from collections import deque
import sys
input=sys.stdin.readline

def BFS():
    point=0
    color=[["white" for _ in range(w)] for _ in range(h)]
    D=[[0 for _ in range(w)] for _ in range(h)]

    queue=deque([])
    for i in range(h):
        for j in range(w):
            if A[i][j]=="#":
                color[i][j]="gray"
                queue.append([i,j])
                D[i][j]=0

    while len(queue)>0:
        x,y=queue.popleft()
        for a,b in [[1,0],[-1,0],[0,1],[0,-1]]:
            X,Y=x+a,y+b
            if 0<=X<h and 0<=Y<w:
                if color[X][Y]=="white":
                    color[X][Y]="gray"
                    D[X][Y]=D[x][y]+1
                    point=max(point,D[X][Y])
                    queue.append([X,Y])
        color[x][y]="black"

    return point

h,w=map(int,input().split())
A=[list(input()) for _ in range(h)]
print(BFS())


from collections import deque
import sys

H, W = [int(_) for _ in input().split()]

M = []
queues = []
for i in range(H):
    A = input()
    M.append(A)
    for j in range(W):
        if A[j] == '#':
            queues.append(deque([[j, i, 0]]))

visited = [[False for _ in range(W)] for _ in range(H)]

max_count = 0
while True:
    for q in queues:
        if len(q) == 0:
            continue
        p = q.popleft()
        x = p[0]
        y = p[1]
        count = p[2]
        max_count = max(max_count, count)
        cands = []
        if x - 1 >= 0:
            cands.append([x-1, y])
        if x + 1 < W:
            cands.append([x+1, y])
        if y - 1 >= 0:
            cands.append([x, y-1])
        if y + 1 < H:
            cands.append([x, y+1])
        for cx, cy in cands:
            if M[cy][cx] == '.' and not visited[cy][cx]:
                q.append([cx, cy, count+1])
                visited[cy][cx] = True
    queues = [q for q in queues if len(q) != 0]
    if len(queues) == 0:
        print(max_count)
        break


import sys
from collections import deque

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

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

def bfs(maze, H, W):
    visited = [[-1] * W for _ in range(H)]
    q = deque([])
    for h in range(H):
        for w in range(W):
            if maze[h][w] == "#":
                visited[h][w] = 0
                q.append((h, w))

    res = 0
    while q:
        h, w = q.popleft()

        for dh, dw in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            nh = h + dh
            nw = w + dw
            if 0 <= nh < H and 0 <= nw < W:
                if visited[nh][nw] == -1 and maze[nh][nw] == ".":
                    visited[nh][nw] = visited[h][w] + 1
                    if res < visited[nh][nw]:
                        res = visited[nh][nw]
                    q.append((nh, nw))

    return res

def main():
    H, W = map(int, input().split())
    S = [input() for _ in range(H)]
    ans = bfs(S, H, W)
    print(ans)

if __name__ == "__main__":
    main()


import queue

def resolve():
    # ★get input
    h, w = map(int, input().split())

    grid = [["" for i in range(w)] for j in range(h)]

    for i in range(h):
        line = input()
        for j in range(w):
            grid[i][j] = line[j:j+1]

    # ★exec
    # BFSにて最短経路を求める
    # 準備
    distance = [[-1 for i in range(w)] for j in range(h)]
    que = queue.Queue()

    # スタート地点の情報を設定
    # 多点スタートの設定
    for i in range(h):
        for j in range(w):
            if grid[i][j] == "#":
                que.put([i, j])
                distance[i][j] = 0

    # BFS開始
    while not que.empty():

        now = que.get()

        # 上下左右のマスを確認
        for move_y, move_x in ((1, 0), (-1, 0), (0, 1), (0, -1)):

            # 盤の範囲外なら何もしない
            target = [now[0] + move_y, now[1] + move_x]
            if not h > target[0] >= 0 or not w > target[1] >= 0:
                continue

            # 黒塗りされているなら何もしない
            if grid[target[0]][target[1]] == '#':
                continue

            # 距離が設定済みなら何もしない
            if not distance[target[0]][target[1]] == -1:
                continue

            # キューに追加
            que.put(target)

            # 最短距離を設定
            distance[target[0]][target[1]] = distance[now[0]][now[1]] + 1

    # 距離が最大の点 = 答えになる。
    ans = 0
    for i in range(h):
        ans = max(ans, max(distance[i]))

    print(ans)

if __name__ == "__main__":
    resolve()


import array
import itertools
from collections import defaultdict, deque

def log(s):
    # print("| " + str(s), file=sys.stderr)
    pass

def output(x):
    print(x, flush=True)

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

def solve():
    def fill(queue):
        footsteps = dict()
        for pp, s in queue:
            footsteps[pp] = -1

        while queue:
            p, s = queue.popleft()
            footsteps[p] = s

            for pp in [(p[0] + 1, p[1]), (p[0] - 1, p[1]), (p[0], p[1] + 1), (p[0], p[1] - 1)]:
                if 0 <= pp[0] < width and 0 <= pp[1] < height and pp not in footsteps:
                    queue.append((pp, s + 1))
                    footsteps[pp] = -1  # placeholder

        return s

    height, width = tuple(input_ints())
    field = [input() for _ in range(height)]
    queue = deque()

    for y, line in enumerate(field):
        for x, c in enumerate(line):
            if c == '#':
                queue.append(((x, y), 0))

    return fill(queue)

def main():
    print(solve())

main()


H, W = map(int, input().split())
state = [[0 if a == '.' else 1 for a in list(input())] for _ in range(H)]

checked = [[False for _ in range(W)] for _ in range(H)]
qs = []
for h in range(H):
    for w in range(W):
        if state[h][w] == 1:
            checked[h][w] = True
            qs.append((h, w))

c = -1
while qs:
    qqs = []
    for h, w in qs:
        nexts = [(h+1, w), (h-1, w), (h, w+1), (h, w-1)]
        for nh, nw in nexts:
            if 0 <= nh <= H-1 and 0 <= nw <= W-1:
                if not checked[nh][nw]:
                    qqs.append((nh, nw))
                    checked[nh][nw] = True
    qs = qqs
    c += 1
print(c)


import numpy as np

H, W = map(int, input().split())
A = [[] for _ in range(H)]
inf = 10 ** 7
for i in range(H):
    A[i] = list(input())
    for j in range(W):
        if A[i][j] == '.':
            A[i][j] = inf
        elif A[i][j] == '#':
            A[i][j] = 0

A = np.array(A)

#print(A)

for j in range(1, W):
    A[:,j] = np.minimum(A[:,j-1]+1, A[:,j])

#print(A)
for j in range(W-2, -1, -1):
    A[:,j] = np.minimum(A[:,j+1]+1, A[:,j])

#print(A)

for i in range(1, H):
    A[i,:] = np.minimum(A[i-1,:]+1, A[i,:])

#print(A)

for i in range(H-2, -1, -1):
     A[i,:] = np.minimum(A[i+1,:]+1, A[i,:])

#print(A)

ans = np.max(A)

#for i in range(H):
#    ans_list.append(max(A[i]))

print(ans)


import copy
import pprint

def check_all(A, H, W):
    for i in range(H):
        for j in range(W):
            if A[i][j] == '.':
                return False
    return True

def flip(A, H, W, i, j):
    if i - 1 >= 0:
        A[i - 1][j] = '#'
    if i + 1 < H:
        A[i + 1][j] = '#'
    if j - 1 >= 0:
        A[i][j - 1] = '#'
    if j + 1 < W:
        A[i][j + 1] = '#'

H, W = map(int, input().rstrip('\n').split())
A = []
for i in range(H):
    A.append(list(input().rstrip('\n')))

count = 0
while True:
    if check_all(A, H, W):
        break
    B = copy.deepcopy(A)
    for i in range(H):
        for j in range(W):
            if A[i][j] == '#':
                flip(B, H, W, i, j)
    print('count =', count)
    pprint.pprint(B)
    print()
    A = B
    count += 1
print(count)


from collections import deque

H, W = map(int, input().split())
A = [list(input()) for i in range(H)]
inf = 1145141919810
B = [[inf]*W for i in range(H)]

Q = deque([])
for i in range(H):
	for j in range(W):
		if A[i][j]=='#':
			B[i][j] = 0
			Q.append([i, j])

ans = 0
while Q != deque([]):
	q = Q.popleft()
	h = q[0]
	w = q[1]
	A[h][w] = 'o'
	ans = max(ans, B[h][w])
	if h-1>=0 and A[h-1][w]=='.':
		Q.append([h-1, w])
		B[h-1][w] = min(B[h-1][w], B[h][w]+1)
	if h+1<H and A[h+1][w]=='.':
		Q.append([h+1, w])
		B[h+1][w] = min(B[h+1][w], B[h][w]+1)
	if w-1>=0 and A[h][w-1]=='.':
		Q.append([h, w-1])
		B[h][w-1] = min(B[h][w-1], B[h][w]+1)
	if w+1<W and A[h][w+1]=='.':
		Q.append([h, w-1])
		B[h][w+1] = min(B[h][w+1], B[h][w]+1)

print(ans)


import copy
def main():
    dict_ = {'#': 1, '.': 0}
    h, w = map(int, (input().split()))
    num = []
    for hh in range(h):
        s = input()
        for ww in range(len(s)):
            if s[ww]=='#':
                num.append(ww + hh * h)
    allnum = [i for i in range(h*w)]
    maxv = 0
    for white in list(set(allnum) - set(num)):
        minv = h*w
        for black in num:
            l1 = abs(white//w - black//w) + abs(white%w - black%w)
            if minv > l1:
                minv = l1
        if maxv < minv:
            maxv = minv
    print(maxv)

if __name__ == '__main__':
    main()


#https://atcoder.jp/contests/agc033/tasks/agc033_a

HW = [int(i) for i in input().split()]
A = []
for i in range(HW[0]):
    A.append(list(str(input())))

B = []
for i in range(len(A)):
    B.append([])
    for j in range(len(A[i])):
        B[i].append(A[i][j])

count = 0
count2 = 0
flag = False
tmp = ['.'] * len(A[0])
while True:
    for i in range(len(A)):
        if i > 0:
            tmp = A[i-1]
        for j in range(len(A[i])):
            if A[i][j] == '.':
                if flag == True:
                    B[i][j] = '#'
                    flag = False
                else:
                    if tmp[j] == '#':
                        B[i][j] = '#'
                    if i < len(A) - 1 and A[i+1][j] == '#':
                        B[i][j] = '#'
                    elif j < len(A[i]) - 1 and A[i][j+1] == '#':
                        B[i][j] = '#'
            else:
                count += 1
                flag = True

    for i in range(len(A)):
        for j in range(len(A[i])):
            A[i][j] = B[i][j]
    if count == HW[0] * HW[1]:
        break
    else:
        count = 0
        count2 += 1

print(count2)


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

for i in range(H):
    word = a[i][0]
    for j in range(W):
        if word[j] == "#":
            A.append([i,j])
        else:
            B.append([i,j])

max = 0
for i in range(len(B)):
    x = B[i][0]
    y = B[i][1]
    min_temp = 0
    min = H * W
    for j in range(len(A)):
        min_temp = abs(x - A[k][0]) + abs(y - A[k][1])
        if min_temp <= min:
            min = min_temp
    if min >= max:
        max = min
print(max)


#import copy
import random

H, W = map(int, input().split())
#dist_matrix = [[10000] * W for i in range(H)]
black_h_list = []
black_w_list = []
for i in range(H):
  line_list = list(input())
  for j in range(W):
    if line_list[j] == "#":
      black_h_list.append(i)
      black_w_list.append(j)

#print(black_h_list)
#print(black_w_list)

max_value = 0
for index in range(100):
  i = int(random.random()*H)
  j = int(random.random()*W)
  min_dist = H+W+2
  for k in range(len(black_h_list)):
    dist = abs(i-black_h_list[k]) + abs(j-black_w_list[k])
    if max_value >= dist:
      min_dist = dist
      break
    elif min_dist > dist:
      min_dist = dist
  #dist_matrix[i][j] = min_dist
  if max_value < min_dist:
    max_value = min_dist

#print(dist_matrix)

print(max_value)


# coding: utf-8
# Your code here!
import collections

h,w = [int(i) for i in input().split()]
board = [input() for j in range(h)] # 縦「n」行

d4 = [[1,0],[0,1],[-1,0],[0,-1]]
memo = [[-1]*w for j in range(h)]
dist = [[100000]*w for j in range(h)]

q = collections.deque()
for i in range(h):
    for j in range(w):
        if board[i][j] == "#":
            memo[i][j] = 1
            q.append((i,j,0))

while len(q) != 0:
#    print(memo)
    i,j,c = q.popleft()
    dist[i][j] = c
    for k in d4:
#        print(k)
        ii,jj = k
        if  i+ii < 0 or i+ii>=h or j+jj <0 or j+jj>=w:
#            print("out",i+ii,j+jj)
            continue
        if memo[i+ii][j+jj] < 0:
#            print("put")
            q.append((i+ii,j+jj,c+1))
            memo[i+ii][j+jj] = 1

ans = 0
for i in range(h):
    for j in range(w):
        ans = max(ans,dist[i][j])

print(ans)
#print(dist)


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

grid = []
for _ in range(w):
    grid.append([x == '#' for x in input()])

maxd = 0
for i in range(h):
    for j in range(w):
        if grid[i][j] is False:
            mind = 10000000
            for ii in range(h):
                for jj in range(w):
                    if grid[ii][jj] is True:
                        d = abs(i - ii) + abs(j - jj)
                        if d < mind:
                            mind = d
            if mind > maxd:
                maxd = mind

print(maxd)


from math import gcd
N = int(input())
As = list(map(int, input().split()))

lis = [0]*N
ans = 0
for k in range(N):
    g = 10**20
    for i in range(N-1):
        if i==k: continue
        for j in range(i+1, N):
            if j==k: continue
            g = min(gcd(As[i], As[j]), g)
    ans = max(ans, g)
if N==2:
    print(max(As))
else:
    print(ans)

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


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

def main2(N,A):
    if N == 2:
        return max(A)
    else:
        max_ = -1
        for i in range(N):
            L = 0
            R = 0

            for j in range(N):
                if i == j: continue
                if j < i:
                    L = gcd(L, A[j])
                else:
                    R = gcd(R, A[j])
            tmp = gcd(L,R)
            if tmp > max_:
                max_ = tmp
        return max_

N = int(input())
A = [int(i) for i in input().split(" ")]
print(main2(N,A))


import math
import copy
N = int(input())
ListA = list(map(int,input().split()))

Answer = 1
if N == 2:
    Answer = math.gcd(ListA[0],ListA[1])
else:
    for j in range(N):
        Lista = copy.deepcopy(ListA)
        Lista.pop(j)
        GCDa = math.gcd(Lista[0],Lista[1])
        proAnswer = GCDa
        for i in range(N-1):
            GCDa = math.gcd(Lista[i],GCDa)
            if GCDa == 1:
                break
            Answer = max(GCDa,proAnswer,Answer)

print(Answer)


from fractions import gcd
from functools import reduce

def gcd_list(numbers):
    return reduce(gcd, numbers)

def main():
    n = int(input())
    A = list(map(int, input().split()))

    gcd_max = 1
    for i in range(n):
        if i == n-1:
            temp = A[i]
            A[i] = A[i-1]
            gcd_max = max(gcd_max, gcd_list(A))
            A[i] = temp
            break
        temp = A[i]
        A[i] = A[i+1]
        gcd_max = max(gcd_max, gcd_list(A))
        A[i] = temp
    print(gcd_max)

if __name__ == '__main__':
    main()


from fractions import gcd
N = int(input())
array = list(map(int,input().split()))
all_gcd = [0]*N
#calc from start to end
gcd_L = [array[0]]
for i in range(N-1):
  gcd_L.append(gcd(gcd_L[-1],array[i+1]))

#calc from end to start
gcd_R = [array[-1]]
for j in range(N-1,0,-1):
  gcd_R.append(gcd(gcd_R[-1],array[j-1]))

gcd_arr = []

for idx in range(N):
  if idx==0:
    gcd_arr.append(gcd_R[-2])
  elif idx==N-1:
    gcd_arr.append(gcd_L[-2])
  else:
    gcd_arr.append(gcd(gcd_L[idx-1],gcd_R[N-1-idx-1]))
print(max(gcd_arr))


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

import math
from functools import reduce

def gcd(numbers):
    return reduce(math.gcd, numbers)
ans = 0
for idx, num in enumerate(A):
  result = gcd(A[:idx:]+A[idx+1::])
  if result > ans:
    ans = result
print(ans)


#C
import fractions
List = []
n = int(input())
A = list(map(int, input().split()))

for j in range(n):
    a = A[:j] + A[j+1:]
    ans = a[0]
    for i in range(1, n-1):
        ans = fractions.gcd(ans, a[i])
    List.append(ans)

print(max(List))