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

import sys
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd

def input(): return sys.stdin.readline().strip()
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

class SegTree:
    """
    以下のクエリを処理する
    1.update:  i番目の値をxに更新する
    2.get_val: 区間[l, r)の値を得る
    """

    def __init__(self, n, func, init):
        """
        :param n: 要素数
        :param func: 値の操作に使う関数(min, max, addなど)
        :param init: 要素の初期値
        """
        n += 1
        self.n = n
        self.func = func
        self.init = init
        # nより大きい2の冪数
        n2 = 1
        while n2 < n:
            n2 <<= 1
        self.n2 = n2
        self.tree = [self.init] * (n2 << 1)

    def update(self, i, x):
        """
        i番目の値をxに更新
        :param i: index(0-indexed)
        :param x: update value
        """
        i += self.n2
        self.tree[i] = x
        while i > 1:
            self.tree[i >> 1] = x = self.func(x, self.tree[i ^ 1])
            i >>= 1

    def get_val(self, a, b):
        """
        [a, b)の値を得る
        :param a: index(0-indexed)
        :param b: index(0-indexed)
        """
        return self._get_val(a, b, 1, 0, self.n2)

    def _get_val(self, a, b, k, l, r):
        """
        [a, b)の値を得る内部関数
        :param k: 現在調べている区間のtree内index
        :param l, r: kが表す区間の左右端index [l, r)
        :return: kが表す区間と[a, b)の共通区間内での最小値。共通区間を持たない場合は初期値
        """
        # 範囲外なら初期値
        if r <= a or b <= l:
            return self.init
        # [a,b)が完全に[l,r)を包含するならtree[k]の値を採用
        if a <= l and r <= b:
            return self.tree[k]
        # 一部だけ範囲内なら2つに分けて再帰的に調査
        m = (l + r) // 2
        return self.func(
            self._get_val(a, b, k << 1, l, m),
            self._get_val(a, b, (k << 1) + 1, m, r)
        )

N=INT()
A=LIST()

st=SegTree(N+2, gcd, 0)
for i in range(N):
    st.update(i+1, A[i])

ans=0
for i in range(1, N+1):
    ans=max(ans, gcd(st.get_val(0, i), st.get_val(i+1, N+2)))
print(ans)


import fractions

integral_count = int(input())
blackboard_integers = list(map(int, input().split()))

gcd_integers = list(set(blackboard_integers))
gcds = [0] * len(gcd_integers)
for i in range(len(gcd_integers)):
    if blackboard_integers.count(gcd_integers[i]) >= 2:
        for n in gcd_integers:
            gcds[i] = fractions.gcd(gcds[i], n)
    else:
        for n in gcd_integers[:i]:
            gcds[i] = fractions.gcd(gcds[i], n)
        for n in gcd_integers[i+1:]:
            gcds[i] = fractions.gcd(gcds[i], n)

print(max(gcds))

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

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.

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.


def gcd(x, y):
    while y != 0:
        x, y = y, x % y
    return x

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

l = [0] * N
r = [0] * N

l[0] = lst[0]
r[-1] = lst[-1]

for i in range(1, N):
    l[i] = gcd(l[i-1], lst[i])

for i in range(N-2, -1, -1):
    r[i] = gcd(r[i+1], lst[i])

ret = max(r[1], l[-2])
for i in range(1, N-1):
    ret = max(ret, gcd(l[i-1], r[i+1]))
print(ret)


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

    if(a < b):
        a, b = b, a
    r = a % b
    while(r != 0):
        a, b = b, r
        r = a % b
    return b

def L(end_i, A):
    if(end_i == 0):
        return 0

    a = 0
    for i in range(end_i):
        a = gcd(a, A[i])
    return a

def R(start_i, A, N):
    if(start_i == N - 1):
        return 0

    a = 0
    for i in range(start_i + 1, N):
        a = gcd(a, A[i])
    return a

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

left = [0] * N
right = [0] * N

for i in range(1, N):
    left[i] = gcd(left[i - 1], A[i - 1])
#print(left)

for i in reversed(range(0, N - 1)):
    right[i] = gcd(A[i + 1], right[i + 1])
#print(right)

M = []
for i in range(N):
    M.append(gcd(left[i], right[i]))
#print(M)

print(max(M))


n=int(input())
a=list(map(int,input().split()))
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
a.sort()
a=a[::-1]
res=[a[0]]
for i in range(1,n):
    for t in res:
        x=gcd(t,a[i])
        if x!=t:
            res.append(x)
res.sort()
print(res[1])


import sys
import math
ni = lambda: int(ns())
na = lambda: list(map(int, input().split()))
ns = lambda: input()

N = ni()
A = na()

def gcd(x,y):
    r = x%y
    while(r!=0):
        x,y = y,r
        r = x%y
    return y
L = []
R = []
l = A[0]
r = A[-1]
for i in range(N-1):
    l = gcd(l,A[i])
    L.append(l)
for i in range(N-1,0,-1):
    r = gcd(r,A[i])
    R.append(r)
M = 0
M = max(R[-1],L[-1])
for i in range(N-2):
    M = max(M,gcd(L[i],R[-(i+2)]))
print(M)


N = int(input())
# スペース区切りの整数の入力
A = list(map(int, input().split()))

def gcd(a, b):
  while b > 0:
    a, b = b, a%b
  return a

ans=[]

if N==2:
  sol=max(A[0],A[1])

else:
  for i in range(3):
    B=A[:]
    del B[i]
    sol=0
    for b in B:
        sol=gcd(sol,b)
    ans.append(sol)
    sol=max(ans)

print(sol)


import fractions
from functools import reduce
import numpy as np

def gcd_list(a, n):
    b = np.array([1]*(n-1))
    for i in range(n-1):
        b[i] = fractions.gcd(a[n-1], a[i])
    b[b.argmin()] = b[b.argmax()]
    return reduce(fractions.gcd, b)

n = int(input())
a = [int(i) for i in input().split()]
print(gcd_list(a, n))


import math
from functools import reduce

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

num=0
x=A[0]
for i in range(N):
    x=A[i]
    A[i]=max(A)
    num=max(num,reduce(math.gcd,A))
    A[i]=x
print(num)


n = int(input())
a = list(map(int,input().split()))
a.sort()
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)
    divisors.sort()
    return divisors
divs = make_divisors(a[0]) #list

divsTF = [0]*len(divs)
for i in range(len(divs)):
    j = [1 if a[_] % divs[i] else 0 for _ in range(n) ]

    if sum(j) <= 1:
        divsTF[i] = 1

ans = 1
for i in range(len(divs)):
    if divsTF[i] == 1:
        ans = max(ans,divs[i])

divs2 = make_divisors(a[1]) #list

divsTF2 = [0]*len(divs2)
for i in range(len(divs2)):
    j = [1 if a[_] % divs2[i] else 0 for _ in range(n) ]

    if sum(j) <= 1:
        divsTF2[i] = 1

aans = 1
for i in range(len(divs2)):
    if divsTF2[i] == 1:
        aans = max(aans,divs2[i])
print(max(aans,ans))


import copy
ans = 1
N = int(input())
A = list(map(int, input().split()))
l = []

def gcd(a,b):
    x = max(a, b)
    y = min(a, b)
    if x % y == 0:
        return y
    else:
        while x % y != 0:
            z = x%y
            x = y
            y = z
        else:
            return z

def gcd_list(list):
    p = 1
    for i in range(len(list)-1):
        if i == 0:
            p = gcd(list[0], list[1])
        else:
            p = gcd(p,list[i+1])
    return p

if N == 2:
    print(gcd(A[0], A[1]))
else:
    for i in range(N):
        l = copy.copy(A)
        l.pop(i)
        ans = max(gcd_list(l), ans)
    print(ans)


import math
import fractions
from functools import reduce
from copy import copy

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

def gcd(*numbers):
    return reduce(fractions.gcd, numbers)

gcds = []
for i in range(N):
    A_ = copy(A)
    A_.pop(i)
    gcds.append(gcd(*A_))

print(max(gcds))


from fractions import gcd

N=int(input())
A=list(map(int,input().split()))
X=[A[0]]
Y=[A[-1]]
for i in range(N):
    X.append(gcd(X[-1],A[i]))
    Y.append(gcd(Y[-1],A[N-1-i]))
X=X[1:]
Y=Y[1:]
Y=Y[::-1]
ans=1
for i in range(N):
    if i==0:
        ans_=Y[i+1]
    elif i==N-1:
        ans_=X[i-1]
    else:
        ans_=gcd(X[i-1],Y[i+1])
    ans=max(ans,ans_)
print(ans)


import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 998244353
inf = float('inf')
ans = []

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

sumA = sum(a)

dp = [[0]*(sumA+1) for _ in range(N)]
start = (sumA+1)//2

dp[0][0] = 2
dp[0][a[0]] = 1

for i in range(N-1):
    for j in range(sumA-a[-1]+1):
        if j<=sumA-a[i+1]:
            dp[i+1][j+a[i+1]] += dp[i][j]
        dp[i+1][j] += dp[i][j]*2

#print(dp)
out = sum(dp[N-1][start:])
ans = (3**N - out*3)%mod
#print(ans)

if sumA%2==0:
    dp2 = [[0] * (sumA + 1) for _ in range(N)]
    dp2[0][0] = 1
    dp2[0][a[0]] = 1

    for i in range(N - 1):
        for j in range(sumA//2 - a[-1] + 1):
            if j <= sumA - a[i + 1]:
                dp2[i + 1][j + a[i + 1]] += dp2[i][j]
            dp2[i + 1][j] += dp2[i][j]
    ans += dp2[N-1][sumA//2]*3
print(ans%mod)

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

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

Sample Output 3

563038556


Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


# ABC120A

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


#!/usr/bin/env python3
a, b, c = map(int, input().split())
print(c) if a * c <= b else print(int(b / a))


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

if b // a < c:
    print(b//a)
else:
    print(c)


a, b, c = map(int, input().split())
if int(b / a) > c:
	print(c)
else:
	print(int(b / a))


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


A, B, C = map(int, input().split())
if B//A <= C:
    print(int(B//A))
else:
    print(int(C))


a,b,c=map(int, input().split())
print(c if a*c<=b else b//a)


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


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

print(min(b // a, c))


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

print(min(C, int(B/A)))


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

print(min(b//a,c))


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

dp = [0]*n
dp[1] = abs(li[1]-li[0])
for i in range(2,n):
    dp[i] = min(dp[i-1]+abs(li[i-1]-li[i]),dp[i-2]+abs(li[i]-li[i-2]))
print(dp)

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


import sys
from sys import stdin,stdout
import math
import random
import heapq
from collections import Counter
from functools import lru_cache
#@lru_cache(maxsize=None) #for optimizing the execution time of callable objects/functions(placed above callable functions)
def mcost(arr,n,dp):
    if n==1:return 0
    if dp[n]!=-1:return dp[n]
    elif n==2:
        dp[n]=abs(arr[1]-arr[0])
        return dp[n]
    elif n==3:
        dp[n]=abs(arr[0]-arr[2])
        return dp[n]
    else:
        dp[n]=min(abs(arr[n-1]-arr[n-2])+mcost(arr,n-1,dp),abs(arr[n-1]-arr[n-3])+mcost(arr,n-2,dp))
        return dp[n]

try:
    for _ in range(1):
        n=int(input())
        arr=[int(i) for i in input().split()]
        dp=[-1]*(n+1)
        print(mcost(arr,n,dp))

except EOFError as e:
    print(e)


N = int(input())
hlis = list(map(int, input().split()))
dp = [-1]*N
dp[0] = 0
dp[1] = abs(hlis[0] - hlis[1])
for i in range(2, N):
    dp[i] = min(dp[i-1]+abs(hlis[i]-hlis[i-1]), dp[i-2]+abs(hlis[i]-hlis[i-2]))
print(dp[-1])


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

dp = [0] * (N+2)

for i in range(N):
    dp[i+1] = min(dp[i+1], dp[i]+abs(h[i]-h[i+1]))
    dp[i+2] = min(dp[i+2], dp[i]+abs(h[i]-h[i+2]))

print(dp[N-1])


import numpy as np

list1=[]

try:
    list1=list(map(int, input().split()))
except:
    quit();

N=list1[0]
W=list1[1]

inp=[]

for _ in range(N):
    try:
        inp.append(list(map(int, input().split())))
    except:
        quit();

inp=np.array(inp)
inp=inp.T
wlist=inp[0]
vlist=inp[1]

dp=np.zeros((N+1,W+1))

for i in range(N+1):
    if i >= 1:
        for j in range(W+1):
            if wlist[i-1] > j:
                dp[i][j]=dp[i-1][j]
            else:
                dp[i][j]=max(dp[i-1][j],dp[i-1][j-wlist[i-1]]+vlist[i-1])

print(int(dp[N][W]))


N, W = map(int, input().split())
w, v = [0] * N, [0] * N
for i in range(N):
	w[i], v[i] = map(int, input().split())

V = sum(v)
# dp[i][j]:i番目までの品物から価値がj以上になるよう選んだときの重さの総和の最小値
dp = [[-1] * (V + 1) for _ in range(N + 1)]
dp[0][0] = 0
for i in range(N):
	for j in range(V + 1):
		# i+1番目を選ぶ場合
		if j - v[i] >= 0:
			dp[i + 1][j] = min(dp[i + 1][j], dp[i][j - v[i]] + w[i])
		# i+1番目を選ばない場合
		dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])

# dp[N][j]がW以下であるようなjの最大値が答えになる
ans = 0
for j in range(V + 1):
	if dp[N][j] <= W:
		ans = j

print(ans)


n = int(input())
h = list(map(int, input().split()))
cost = [0]*n
cost[0] = 0
cost[1] = abs(h[0] - h[1])
for i in range(2, n):
    cost[i] = min(cost[i-2]+abs(h[i-2]-h[i]), cost[i-1]+abs(h[i-1]-h[i]))
print(cost[-1])


N = int(input())
h = [int(_) for _ in input().split()]
dp = [0,abs(h[1]-h[0])]
for i in range(2,N):
    dp.append(min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2])))
print(dp[-1])


n = int(input())
l = list(map(int, input().split()))
#print(l)
dp = [0]*n
dp[1] = abs(l[1]-l[0])
for i in range(1,n-1):
  dp[i+1] = min(dp[i]+abs(l[i+1]-l[i]), dp[i-1]+abs(l[i+1]-l[i-1]))
print(dp[-1])


#入力:[n1,n2,...nk](int:整数配列)
def input_array():
	return list(map(int,input().split()))

#入力:N,M(int:整数)
def input2():
	return map(int,input().split())

n,k=input2()
H=input_array()
INF=10**9
# 最小化問題
dp=[INF]*n
# 初期化
dp[0]=0
flag=True

for i in range(n):
	for j in range(1,k+1):
		if i+j>=n:
			flag=False
			break
		a=dp[i]+(abs(H[i+j]-H[i]))
		dp[i+j]=min(dp[i+j],a)
	if flag==False:
		break

print(dp[-1])

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


n, k = map(int, input().split())
h = tuple(map(int, input().split()))

cost = [float("INF")] * n
cost[0] = 0

for i in range(1, n):
  for j in range(1, min(i, k) + 1):
    cost[i] = min(cost[i], cost[i - j] + abs(h[i] - h[i - j]))

print(cost[-1])


def main():
    n, k = map(int, input().split())
    stns = list(map(int, input().split()))
    INF = 10**9
    dp = n * [INF]
    dp[0] = 0
    k = k + 1
    for i in range(n):
        for j in range(1, k):
            j = j + i
            try: dp[j] = min(dp[j], dp[i] + abs(stns[i] - stns[j]))
            except: pass
    print(dp[-1])

if __name__ == "__main__":
    main()


def main():
    def chmin(i,j):
        dp[i] = min(dp[i], dp[i-j] + abs(h[i] - h[i-j]))

    N,K = (int(x) for x in input().split())
    h = [int(x) for x in input().split()]
    dp = [float('INF')]*N
    dp[0] = 0

    for i in range(1, N):
        if i <= K:
            for j in range(1, i+1):
                chmin(i,j)
        else:
            for j in range(1, K+1):
                chmin(i,j)
    print(dp[-1])

if __name__ == '__main__':
    main()


import sys
n,k = map(int,input().split())
l = list(map(int, input().split()))
dp = [sys.maxsize] *n
dp[0] = 0
for i in range(n):
    for j in range(i+1,i+k+1):
        if(j<n):
            dp[j]=min(dp[j],dp[i]+abs(l[i]-l[j]))
print(dp[n-1])


import sys
input = sys.stdin.readline

############ ---- Input Functions ---- ############
def inp():
    return(int(input()))
def inlt():
    return(list(map(int,input().split())))
def insr():
    s = input()
    return(list(s[:len(s) - 1]))
def invr():
    return(map(int,input().split()))

n, kk = invr()
stones = inlt()

if n == 0:
	print 0

#print n, kk

inf = 2 ** 31
# dp[i] states the minimum cost to stones 1....i
dp = [inf for _ in range(len(stones))]
dp[0] = 0

for i in range(1, len(dp)):
	for k in range(1, kk + 1):
		if i - k >= 0:
			dp[i] = min(dp[i], dp[i-k] + abs(stones[i] - stones[i-k]))

print dp[-1] if dp[-1] != inf else 0


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

DP = [1000000]*N
DP[0] = 0
for i in range(N):
    for j in range(i + 1, min(N, i + K + 1)):
        DP[j] = min(DP[j], DP[i] + abs(High[i] - High[j]))
print(DP[N-1])


import sys

n,k = list(map(int, input().split(" ")))
l = list(map(int, input().split(" ")))
l = [999999]*k + l
dp= [0]*(n+k)

for i in range( k + 1, n+k):
	dp[i] = min([ dp[i - j] + abs(l[i] - l[i - j]) for j in range(1, k + 1) ])

print(dp[n + k - 1])


n,k=map(int,input().split())
h=list(map(int,input().split()))
dp=[10**6]*n
dp[0]=0
for i in range(0,n):
    for j in range(i+1,min(i+k+1,n)):
        dp[j]=min(dp[i]+abs(h[i]-h[j]),dp[j])
print(dp[n-1])


#dp[i]:i番目の足場に達した時のコストの最小値
#dp[i] = min(dp[i-k]+abs(h[i]-h[i-k])) (1<=k<=K)
#このままだとO(NK)で間に合わない?

N, K = map(int, input().split())
h = list(map(int, input().split()))
inf = 10**18

dp = [inf for i in range(N)]
dp[0] = 0
dp[1] = abs(h[1]-h[0])

for i in range(2, N):
    for j in range(1, min(K+1, i+1)):
        if dp[i] > dp[i-j] + abs(h[i]-h[i-j]):
            dp[i] = dp[i-j] + abs(h[i]-h[i-j])

print(dp[N-1])


def main(lines):
    n, k = map(int, lines[0].split())
    h = list(map(int, lines[1].split()))
    h.extend([0] * 101)
    dp = [1000000] * (100100)
    dp[0] = 0
    for i in range(n):
        for j in range(k + 1):
            temp = dp[i] + abs(h[i] - h[i + j])
            if dp[i + j] > temp:
                dp[i + j] = temp
    print(dp[n - 1])

import sys
if __name__ == '__main__':
    lines = []
    for l in sys.stdin:
        lines.append(l.rstrip('\r\n'))
    main(lines)


n,k=map(int,input().split())
l=list(map(int,input().split()))
dp=[0]*n
dp[0]=0
for i in range(1,n):
    s=min(k,i)+1
    ans=999999999
    for j in range(1,s):
        ans=min(ans,dp[i-j]+abs(l[i]-l[i-j]))
    dp[i]=ans
print(dp[n-1])


# 足場数,最大跳躍数
n, k = [int(x) for x in input().split()]

# DPテーブル
dp = [10 ** 9 for _ in range(n + 2)] # ちょっと大きめに

# 初期値
# 足場0から足場0に移動するコストを意味する
dp[0] = 0

# 各足場における高さ
h = [int(x) for x in input().split()]

# 全足場に対して
for i in range(1, n):
  for d in range(1, k+1):
    if i - d >= 0:
      total_cost = dp[i-d] + abs(h[i] - h[i-d])
      dp[i] = min(dp[i], total_cost)

# 最終足場のコスト
print(dp[n - 1])


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

def dif(a, b):
	if a>=b:
		return a-b
	else:
		return b-a

dp = [0]*1000000
dp[0]=0
dp[1]=dif(h[0],h[1])
for i in range(n-2):
	x = i+2
	dp[x] = dp[x-1]+dif(h[x],h[x-1])
	for t in range(k):
		j=t+1
		if x-j < 0:
			break
		dp[x] = min(dp[x],dp[x-j]+dif(h[x],h[x-j]))
print(dp[n-1])
#print(dp[0:n])


import numpy as np
n, k = map(int,input().split())
a = np.array(list(map(int,input().split())))
dp_table = np.zeros(n)
for i in range(1,n):
    dp_table[i] = np.min(np.abs(a[max(0,i-k):i] - a[i]) + dp_table[max(0,i-k):i])
print(int(dp_table[-1]))


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

    dp = [float('inf') for i in range(n)]
    dp[0] = 0
    for i in range(1, n):
        for j in range(1, k + 1):
            # if i - j < 0:
            #     break
            dp[i] = min(dp[i + j], dp[i] + abs(heights[i] - heights[i + j]))

    print(dp[n - 1])

if __name__ == '__main__':
    main()


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

steps = [int(i) for i in input().split()]
dp = [9999999] * n

dp[0] = 0

for i in range(1, n):
    for j in range(1, k + 1):
        if i - j >= 0:
            temp2 = dp[i-j] + abs(steps[i] - steps[i-j])
            if dp[i] > temp2:
                dp[i] = temp2
        else:
            continue

print(dp[n - 1])


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

dp = np.zeros(N,dtype=int)
for i in range(1,N):
    dp[i] = (dp[max(0,i-K-1):i] + np.abs(h[i]-h[max(0,i-K-1):i])).min()
print(dp[-1])


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

# dpの最小値を変更する関数
def chmin(a, b):
    if a > b:
        return b
    else:
        return a

# 無限大の値
f_inf = float('inf')

# DP テーブルを初期化　(最小化問題なので INF に初期化)
dp = [f_inf] * (10**5+10)

# 初期条件
dp[0] = 0

# 足場 i-1 から足場 i へと移動する。コストは|h[i]−h[i-1]|
# 足場 i-2 から足場 i へと移動する コストは |h[i]−h[i-2]|
# 足場 i-j から足場 i へと移動する。コストは |h[i]−h[i-j]|
for i in range(1, n):
    for j in range(1, k+1):
        # i-kが負の場合は、スタートはh[0]になる。
        if i-k<0:
            dp[i] = abs(h[i]-h[0])
        else:
            dp[i] = chmin(dp[i], dp[i - j] + abs(h[i] - h[i - j]))

print(dp[n-1])


N, K = map(int, input().split())
H = list(map(int, input().split()))
INF = 10 ** 9
dp = [INF] * N
dp[0] = 0

for i in range(N - 1):
  for k in range(1, K + 1):
    if i + k >= N: break
    dp[i + k] = min(dp[i + k], dp[i] + abs(H[i] - H[i + k]))

print(dp[-1])


#frog2
H=10**10
n,K=map(int,input().split())
h=list(map(int,input().split()))+[H]*10
dp=[0]*(n+10)
for i in range(1,n+1):
    lis=[dp[i-k]+abs(h[i]-h[i-k]) for k in range(1,K+1)]
    dp[i]=min(lis)
print(dp[n-1])


import numpy as np
INF = 2**60
N, W = map(int, input().split())
wv = [map(int, input().split()) for i in range(N)]
dp = np.full((N+1, W+1), -INF, dtype = np.int)
dp[0][0] = 0 # 初期条件
for i, (w, v) in enumerate(wv):
    dp[i+1] = np.maximum(dp[i+1], dp[i])
    dp[i+1][w:] = np.maximum(dp[i+1][w:], dp[i][:-w] + v)
print(np.max(dp[N][:W]))

Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^5

1 \leq w_i \leq W

1 \leq v_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

5 5
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 2

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


import sys
import collections as cc
input = sys.stdin.readline
I=lambda:list(map(int,input().split()))
n,w=I()
val=[]
wt=[]
for i in range(n):
	x,y=I()
	wt.append(x)
	val.append(y)
dp=[[0]*(w+1) for i in range(n+1)]
for i in range(1,n+1):
	for j in range(1,w+1):
		if wt[i-1]<=j:
			dp[i][j]=max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j])
		else:
			dp[i][j]=dp[i-1][j]
print(dp[n][w])


import sys

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

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

def main():
    N, W = map(int, input().split())
    item = []
    for _ in range(N):
        w, v = map(int, input().split())
        item.append((w, v))

    dp = [0] * (W + 1)
    for w, v in item:
        for i in range(W + 1)[::-1]:
            if i - w >= 0:
                tmp = dp[i - w] + v
                if tmp > dp[i]:
                    dp[i] = tmp

    print(max(dp))

if __name__ == "__main__":
    main()


def knapsack(weight,value,N,W,i,cache):
    if i == N or W <= 0:
        return 0
    if cache[i][W] != 0:
        return cache[i][W]
    op1,op2 = 0,0
    if weight[i] <= W:
        op1 = value[i] + knapsack(weight,value,N,W-weight[i],i+1,cache)
    op2 = knapsack(weight,value,N,W,i+1,cache)
    cache[i][W] = max(op1,op2)
    return cache[i][W]

N,W = map(int,input().split())
weight = []
value = []
for i in range(N):
    w,v = map(int,input().split())
    weight.append(w)
    value.append(v)
cache = [[0 for i in range(W+1)] for j in range(N+1)]
print(knapsack(weight,value,N,W,0,cache))


import numpy as np
N, W = map(int, input().split())
dp = np.zeros((N+1, W+1), dtype=int)

w,v = [],[]
for _ in range(N):
    w_,v_ = map(int,input().split())
    w.append(w_)
    v.append(v_)

for row in range(N):
    dp[row+1,:w[row]] = dp[row,:w[row]]
    dp[row+1,w[row]:] = np.maximum(dp[row,w[row]:],v[row]+dp[row,:-w[row]])

print(dp[N,-1])


def solve(cost,weight,n,m):
    dp=[[0]*(m+1) for i in range(n+1)]
    for i in range(1,n+1):
        for j in range(1,m+1):
            if(weight[i-1]>j):
                dp[i][j]=dp[i-1][j]
            else:
                dp[i][j]=max(dp[i-1][j],cost[i-1]+dp[i-1][j-weight[i-1]])

    # for i in range(len(dp)):
    #     print(dp[i])
    return dp[-1][-1]

n,m=map(int,input().split())
cost=[]
weight=[]
for _ in range(n):
    a,b=map(int,input().split())
    weight.append(a)
    cost.append(b)
dp=[[0]*n for i in range(n)]

print(solve(cost,weight,n,m))


N,W = map(int,input().split())
w,v = [0]*N , [0]*N
for i in range(N):
  w[i],v[i] = map(int,input().split())
dp = [[0]*(W+1) for _ in range(N+1)]
for k in range(W+1):
  dp[0][k] = 0
for i in range(N):
  for j in range(W+1):
    if j -w[i] <0:
      dp[i+1][j] = dp[i][j]
    else:
      dp[i+1][j] = max(dp[i][j], dp[i][j-w[i]]+v[i])
print(dp[-1][W])


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

def main():
    n, w = map(int, input().split())
    items = [tuple(map(int, input().split())) for i in range(n)]

    dp = [[0] * (w + 1) for i in range(n + 1)]

    for i, item in enumerate(items):
        for i_w in range(w + 1):
            if i_w >= item[0]:
                dp[i + 1][i_w] = max(dp[i][i_w - item[0]] + item[1], dp[i][i_w])
            else:
                dp[i + 1][i_w] = dp[i][i_w]

    print(dp[n][w])

if __name__ == '__main__':
    main()


import sys
sys.setrecursionlimit(10000000)

N, W = map(int,input().split())
H = list(list(map(int,input().split())) for _ in range(N))
#sub problem: max cost from 0 to ith day
memo = {}

def rec(num_of_item, left_w):
  if (num_of_item, left_w) in memo:
    return memo[(num_of_item, left_w)]
  if num_of_item == N:
    return 0
  w, v = H[num_of_item]
  if left_w - w < 0:
    memo[(num_of_item, left_w)] = rec(num_of_item + 1, left_w)
    return memo[(num_of_item, left_w)]
  memo[(num_of_item, left_w)] = max(v + rec(num_of_item + 1, left_w - w), rec(num_of_item + 1, left_w))
  return memo[(num_of_item, left_w)]
print(rec(0, W))


import sys
sys.setrecursionlimit(10**8)
N, L = map(int, input().split())
W = []
V = []
for _ in range(N):
    w, v = map(int, input().split())
    W.append(w)
    V.append(v)

dp = [[-1] * (L+100) for _ in range(N+10)]

def knap(i, j):
    if dp[i][j] >= 0:
        return dp[i][j]

    if i == N:
        dp[i][j] = 0
    elif j < W[i]:
        dp[i][j] = knap(i+1, j)
    else:
        dp[i][j] = max(knap(i+1, j), knap(i+1, j - W[i]) + V[i])

    return dp[i][j]

print(knap(0, L))


N, W = map(int, input().split())
w_list = []
v_list = []
for i in range(N):
    w, v = map(int, input().split())
    w_list.append(w)
    v_list.append(v)
dp = [[0 for i in range(W+1)] for i in range(N)]
for i in range(N):
    w = w_list[i]
    v = v_list[i]
    for j in range(W+1):
        if j-w >= 0:
            dp[i][j] = max(dp[i-1][j], dp[i-1][j-w]+v)
        else:
            dp[i][j] = dp[i-1][j]
print(dp[N-1][W])


def solve(N, W, weight_values):
  dp = [[0 for _ in range(W + 1)] for _ in range(N + 1)]
  dp[0][0] = 1

  for i in range(N + 1):
    i_weight, i_value = weight_values[i - 1]
    for w in range(i_weight, W + 1):
      dp[i][w] = max(dp[i - 1][w - i_weight] + i_value, dp[i - 1][w])

  print(dp[N][W])

N, W = iln()
w_v = []
for i in range(N):
  w_v = iln()

solve(N, W, w_v)


n,m=map(int,input().split())
d=[ list(map(int,input().split()))  for i in range(n)]
dp=[0]*(m+2)

for i in range(n):  #商品を一つずつ見ていく。
  for j in range(m+1,d[i][0],-1): #w~(限界-w)までのdpの箱に入れていく。(例)w,m=3,8なら3~5
    dp[j]=max(dp[j-d[i][0]]+d[i][1],dp[j]) #d[i][0]=w d[i][1]=v

print(dp[m+1])


from itertools import count

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

dp = [[0]*(W+1) for _ in range(N+1)]

for i in range(N):
    for w in range(W+1):
        if w - WV[i][0] >= 0:  # 品物を追加できるとき
            dp[i+1][w] = max(dp[i+1][w], dp[i][w-WV[i][0]] + WV[i][1])
        # できないとき
        dp[i+1][w] = max(dp[i+1][w], dp[i][w])
print(dp)
print(dp[N][W])


N, W = map(int, input().split())
dp = [-1] * (W+1)
dp[0] = 0

for i in range(N):
    w, v = map(int, input().split())
    for j in range(W-w, -1, -1):
        if dp[j] >= 0:
            dp[j+w] = max(dp[j+w], dp[j] + v)

ans = max(dp)
print(ans)


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

dp = [[float('-inf') for _ in range(1000)] for _ in range(110)]
dp[0][0] = 0
for i, (item_weight, item_value) in enumerate(items):  # i番目の品
    for total_weight in range(W+10):                   # 重さの合計
        dp[i+1][total_weight] = max(dp[i][total_weight], dp[i+1][total_weight])
        dp[i+1][total_weight+item_weight] = max(dp[i][total_weight]+item_value, dp[i+1][total_weight+item_weight])

print(dp[N][W])


import sys

memo = {}
def get_key(idx, w):
	return str(idx) + ":" + str(w)

#Errichto's implementation
def knapsack(n, w, weights, vals):
	dp = [0] * (w+1)
	for i in xrange(0, n):
		for w_a in xrange(w-weights[i], -1, -1):
			#print "weight already:", w_a
			#print "w[i]:", weights[i]
			#print "dp[w_a+ weights[i]", dp[weights[i]+w_a]
			#print "dp[w_a]:", dp[w_a]
			dp[weights[i]+w_a] = max(dp[weights[i]+w_a], dp[w_a] + vals[i])
			#print "setting dp[w_a+ weights[i]", dp[weights[i]+w_a]
	max_val = 0;
	for j in xrange(w+1):
		max_val = max(max_val, dp[j])
	return max_val

def knapsack_rec(n, w, weights, vals, idx):
	if idx == n:
		return 0
	if w == 0:
		return 0
	key_str = get_key(w, idx)
	if key_str in memo.keys():
		return memo[key_str]

	if weights[idx] > w:
		memo[key_str] = knapsack_rec(n, w, weights, vals, idx+1)
	else:
		memo[key_str] =  max(knapsack_rec(n, w-weights[idx], weights, vals, idx+1) + vals[idx],
							 knapsack_rec(n, w, weights, vals, idx+1))
	return memo[key_str]

def knapsack_2d(n, w, weights, vals):
	dp = [[0] * (w+1) for i in xrange(n+1)]
	for i in xrange(1, n+1):
		for j in xrange(1, w+1):
			if weights[i-1] > j:
				dp[i][j] = dp[i-1][j]
			else:
				dp[i][j] = max(dp[i-1][j], vals[i-1] + dp[i-1][j-weights[i-1]])
	#rint dp
	return dp[n][w]

def read_input():
	#Read the input N
	a = sys.stdin.readline().split()
	n = int(a[0])
	w = int(a[1])
	w_l = [0] * n
	v_l = [0] * n
	for i in xrange(n):
		a = sys.stdin.readline().split()
		w_l[i] = int(a[0])
		v_l[i] = int(a[1])
	result = knapsack(n, w, w_l, v_l)
#	result = knapsack_rec(n, w, w_l,v_l, 0)
	print result

if __name__ == '__main__':
	 read_input()


w = []
v = []
n, W = map(int, input().split())
#dp = [[0 for i in range(n)] for j in range(W)]
dp = [[None for i in range(W+1)] for j in range(n+1)]

for i in range(n):
    v1, v2 = map(int, input().split())
#    v2, v1 = map(int, input().split())
    w.append(v1)
    v.append(v2)

# i: Index (Tracing all items)
# j: Remaining weight
# Return the sum of value
def knap(i, j):
    # print("\n# i: " + str(i))
    # print("# j: " + str(j))
    if dp[i][j] is not None:
        return dp[i][j]

    res = 0

    if i == n:
#        dp[i][j] = 0
        res = 0
    elif j < w[i]:
        res = knap(i+1, j)
    else:
        # if dp[i][j] is None:
        #     dp[i][j] = dp[i-1][j] + v[i]
        res = max(knap(i+1, j), knap(i+1, j-w[i]) + v[i])

    dp[i][j] = res
    return dp[i][j]
#    return res

print(knap(0, W))


import sys
from collections import Counter
N, W = map(int, input().split())

dp = Counter()
dp[0] = 0

for _ in range(N):
    w, v = map(int, sys.stdin.readline().split())
    for k in dp.copy().keys():
        if k + w <= W:
            dp[k + w] = max(dp[k + w], dp[k] + v)

print(max(dp.values()))


n,w_max=map(int,input().split())
W,V=[],[]
for i in range(n):
  w,v=map(int,input().split())
  W.append(w)
  V.append(v)
DP=[[0 for i in range(w_max+1)] for j in range(n)]
for i in range(w_max+1):
  if i>=W[0]:
    DP[0][i]=V[0]
for i in range(1,n):
  for j in range(w_max+1):
    if j>W[i]:
      DP[i][j]=max(DP[i-1][j],DP[i-1][j-W[i]]+V[i])
    elif j==W[i]:
      DP[i][j]=max(DP[i-1][j],V[i])
    else:
      DP[i][j]=DP[i-1][j]
print(DP[n-1][w_max])


from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy

sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): pass
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

s = S()
t = S()
S,T = len(s),len(t)
dp = [[0]*(T+1) for _ in range(S+1)]
for i in range(S):
    for j in range(T):
        if s[i]==t[j]:
            dp[i+1][j+1] = 1 + dp[i][j]
        else:
            dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])

ans = ""
while dp[S][T]:
    if dp[S][T] == dp[S-1][T-1] + 1:
        S -= 1
        T -= 1
        ans = s[S] + ans
    elif dp[S][T] == dp[S - 1][T]:
        S -= 1
    else:
        T -= 1

if len(ans) == 0:
    print("")
else:
    print(ans)

Score : 100 points

Problem Statement

You are given strings s and t.
Find one longest string that is a subsequence of both s and t.

Notes

A subsequence of a string x is the string obtained by removing zero or more characters from x and concatenating the remaining characters without changing the order.

Constraints

s and t are strings consisting of lowercase English letters.

1 \leq |s|, |t| \leq 3000

Input

Input is given from Standard Input in the following format:

s
t

Output

Print one longest string that is a subsequence of both s and t.
If there are multiple such strings, any of them will be accepted.

Sample Input 1

axyb
abyxb

Sample Output 1

axb

The answer is axb or ayb; either will be accepted.

Sample Input 2

aa
xayaz

Sample Output 2

aa

Sample Input 3

a
z

Sample Output 3

The answer is (an empty string).

Sample Input 4

abracadabra
avadakedavra

Sample Output 4

aaadara


import sys
readline = sys.stdin.readline

S = readline().rstrip()
T = readline().rstrip()

# dp[i][j] = Sをi文字目、Tをj文字目まで進めたときの最長
# S[i] == S[j]のとき
# dp[i][j] = dp[i - 1][j - 1] + 1
# S[i] != S[j]のとき
# dp[i][j] = max(dp[i - 1][j],dp[i][j - 1])

# その際、自分がどこから来たか？を記録する
# dp[i - 1][j] > dp[i][j - 1]であれば
# route[i][j] = (i,j)を記録

dp = [[0] * (len(T) + 1) for i in range(len(S) + 1)]

for i in range(len(S)):
  for j in range(len(T)):
    if S[i] == T[j]:
      dp[i + 1][j + 1] = dp[i][j] + 1
    else:
      if dp[i][j + 1] > dp[i + 1][j]:
        dp[i + 1][j + 1] = dp[i][j + 1]
      else:
        dp[i + 1][j + 1] = dp[i + 1][j]

# dpテーブルの数字を見て復元していく
ans = ""
x = len(S)
y = len(T)
while x != 0 and y != 0:
  if dp[x][y] == dp[x - 1][y]: # x - 1から遷移してきた
    x -= 1
  elif dp[x][y] == dp[x][y - 1]: # y - 1から遷移してきた
    y -= 1
  else:
    ans += S[x - 1]
    x -= 1
    y -= 1

print(ans[::-1])


s=input()
t=input()
n=len(s)
m=len(t)
dp=[[0 for x in range(n+1)] for y in range(m+1)]
for i in range(1,m+1):
    for j in range(1,n+1):
        if(s[j-1]==t[i-1]):
            dp[i][j]=1+dp[i-1][j-1]
        else:
            temp=max(dp[i-1][j],dp[i][j-1])
            dp[i][j]=temp
i,j=m,n
ans=''
while (i>0 and j>0):
    if(s[j-1]==t[i-1]):
        ans+=s[j-1]
        i-=1
        j-=1
    else:
        if(dp[i-1][j]>dp[i][j-1]):
            i-=1
        else:
            j-=1
print(ans[::-1])


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

# start your code here:

def solve(i, j):
    if(i==Ls or j==Lt):
        return ""
    elif(s[i]==t[j]):
        if(dp[i][j]==-1):
            foo = str(s[i]) + solve(i+1, j+1)
            dp[i][j] = foo
            return foo
        else:
            return dp[i][j]
    else:
        if(dp[i][j]==-1):
            temp1 = solve(i+1, j)
            temp2 = solve(i, j+1)

            if(len(temp1)>len(temp2)):
                dp[i][j] = temp1
                return temp1
            dp[i][j] = temp2
            return temp2
        else:
            return dp[i][j]

s = STR()
t = STR()
Ls = len(s)
Lt = len(t)
dp = list2d(3001, 3001, -1)
print(solve(0, 0))


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

#A
def A():
    """
    N個の足場があります。足場には1,2,…,Nと番号が振られています。
    各i (1≤i≤N) について、足場 i の高さは hi です。
    最初、足場 1 にカエルがいます。 カエルは次の行動を何回か繰り返し、足場 N まで辿り着こうとしています。
    足場 i にいるとき、足場 i+1 または i+2 へジャンプする。
    このとき、ジャンプ先の足場を j とすると、コスト |hi−hj| を支払う。
    カエルが足場 N に辿り着くまでに支払うコストの総和の最小値を求めてください。

    制約
        入力はすべて整数である。
    2≤N≤10**5
    1≤hi≤10**4
    """
    n = II()
    h = LI()
    dp = [0 for i in range(n)]
    dp[1] = abs(h[0] - h[1])
    for i in range(2,n):
        dp[i] = min(dp[i - 1] + abs(h[i - 1] - h[i]), dp[i - 2] + abs(h[i - 2] - h[i]))
    print(dp[n-1])
    return

#B
def B():
    n, K = LI()
    h = LI()
    dp = [float("INF") for i in range(n + K + 1)]
    dp[0] = 0
    for i in range(n):
        for k in range(1, K + 1):
            if i + k >= n:
                break
            dp[i + k] = min(dp[i + k], dp[i] + abs(h[i] - h[i + k]))
    print(dp[n-1])
    return

#C
def C():
    n = II()
    abc = LIR(n)
    dp = [0 for i in range(3 * n + 1)]
    dp[0] = abc[0][0]
    dp[1] = abc[0][1]
    dp[2] = abc[0][2]
    for i in range(1,n):
        dp[3 * i] = max(dp[3 * i], dp[3 * (i - 1) + 1] + abc[i][0], dp[3 * (i - 1) + 2] + abc[i][0])
        dp[3 * i + 1] = max(dp[3 * i + 1], dp[3 * (i - 1) + 2] + abc[i][1], dp[3 * (i - 1)] + abc[i][1])
        dp[3 * i + 2] = max(dp[3 * i + 2], dp[3 * (i - 1) + 1] + abc[i][2], dp[3 * (i - 1)] + abc[i][2])
    dp[3 * n] = max(dp)
    print(dp[3*n])

    return

#D
def D():
    """N個の品物があります。 品物には 1,2,…,Nと番号が振られています。
    各 i (1≤i≤N) について、品物i の重さはwi で、価値はvi です。
    太郎君は、N 個の品物のうちいくつかを選び、ナップサックに入れて持ち帰ることにしました。
    ナップサックの容量は W であり、持ち帰る品物の重さの総和は W以下でなければなりません。
    太郎君が持ち帰る品物の価値の総和の最大値を求めてください

    入力はすべて整数である。
    1≤N≤100
    1≤W≤10**5
    1≤wi≤W
    1≤vi≤10**9"""
    n, w = LI()
    wv = LIR(n)
    dp = [[0 for k in range(w + 1)] for i in range(n + 2)]
    for i in range(1,n + 1):
        for j in range(w + 1):
            if j < wv[i-1][0]:
                dp[i + 1][j] = dp[i][j]
            else:
                dp[i + 1][j] = max(dp[i][j], dp[i][j - wv[i - 1][0]] + wv[i - 1][1])
    print(dp[n+1][w])

    return

#E
def E():
    """N個の品物があります。 品物には 1,2,…,Nと番号が振られています。
    各 i (1≤i≤N) について、品物i の重さはwi で、価値はvi です。
    太郎君は、N 個の品物のうちいくつかを選び、ナップサックに入れて持ち帰ることにしました。
    ナップサックの容量は W であり、持ち帰る品物の重さの総和は W以下でなければなりません。
    太郎君が持ち帰る品物の価値の総和の最大値を求めてください

    入力はすべて整数である。
    1≤N≤100
    1≤W≤10**9
    1≤wi≤W
    1≤vi≤10**3"""
    n, w = LI()
    wv = LIR(n)
    dp = [[float("INF") for i in range(10 ** 5 + 1)] for k in range(n + 1)]
    dp[0][0] = 0
    for i in range(n):
        for k in range(10 ** 5 + 1):
            if k < wv[i][1]:
                dp[i + 1][k] = dp[i][k]
            else:
                dp[i + 1][k] = min(dp[i][k], dp[i][k - wv[i][1]] + wv[i][0])
    ans = 0
    for i in range(10 ** 5 + 1):
        if dp[n][i] <= w:
            ans = i
    print(ans)

    return

#F
def F():
    s = S()
    t = S()
    ss = len(s)
    tt = len(t)
    dp = [[0] * (tt + 1) for k in range(ss + 1)]
    for i, si in enumerate(s):
        dpi1 = dp[i + 1]
        dpi = dp[i]
        for j, tj in enumerate(t):
            if si == tj:
                dpi1[j + 1] = dpi[j] + 1
            else:
                if dpi[j + 1] < dpi1[j]:
                    dpi1[j + 1] = dpi1[j]
                else:
                    dpi1[j + 1] = dpi[j + 1]
    ans = deque()
    si = ss
    ti = tt
    while si > 0 and ti > 0:
        if dp[si][ti] == dp[si - 1][ti]:
            si -= 1
        elif dp[si][ti] == dp[si][ti - 1]:
            ti -= 1
        else:
            si -= 1
            ti -= 1
            ans.appendleft(s[si])
    print("".join(ans))
    return

#G
def G():
    n, m = LI()
    xy = LIR_(m)
    edge = [[] for i in range(n)]
    for x,y in xy:
        edge[x].append(y)
    dp = [0 for i in range(n)]
    def ans(dp, i):
        #print(dp, i)
        if dp[i] != 0:
            return dp[i]
        else:
            if len(edge[i]) == 0:
                return 0
            ansb = 0
            for k in edge[i]:
                #print(dp, k , i)
                ansb = max(ansb, ans(dp, k) + 1)
                dp[i] = max(ansb, dp[i])
                #print(dp)
            return ansb

    for i in range(n):
        dp[i] = ans(dp, i)
    print(max(dp))
    return

#H
def H():
    h, w = LI()
    a = SR(h)
    dp = [[0 for i in range(w)] for k in range(h)]
    for i in range(w):
        if a[0][i] == "#":
            break
        dp[0][i] = 1
    for i in range(h):
        if a[i][0] == "#":
            break
        dp[i][0] = 1
    for i in range(1,w):
        for k in range(1, h):
            #print(i,k, dp)
            if a[k - 1][i] == ".":
                if a[k][i - 1] == ".":
                    dp[k][i] = dp[k - 1][i] + dp[k][i - 1] % mod
                else:
                    dp[k][i] = dp[k - 1][i]
            else:
                if a[k][i - 1] == ".":
                    dp[k][i] = dp[k][i - 1]
    print(dp[h-1][w-1] % mod)

    return

#I
def I():
    n = II()
    p = LF()
    dp = [[0 for k in range(n+1)] for i in range(n+1)]
    dp[1][1] = p[0]
    dp[1][0] = 1-p[0]
    for i in range(2,n+1):
        for k in range(i + 1):
            if k == 0:

                dp[i][k] = dp[i-1][k] * (1 - p[i-1])
            else:
                dp[i][k] = dp[i - 1][k - 1] * p[i - 1] + dp[i - 1][k] * (1 - p[i - 1])
    #print(dp)
    print(sum(dp[n][n//2+1:]))
    return
#J
def J():
    n = II()
    a = LI()

#K
def K():
    n, k = LI()
    an = LI()
    dp = [0 for i in range(k + 1)]
    dp[0] = 0
    ans = ["First","Second"]
    for i in range(k + 1):
        if i in an:
            dp[i] = 0
        else:
            for num, a in enumerate(an):
                if a < i:
                    if dp[i - a] == 1:
                        dp[i] = 0
                        break
            else:
                dp[i] = 1
        #print(dp,i)

    print(ans[dp[k]])

#L
def L():
    N, K = LI()
    an = LI()
    dp = [[1 for k in range(K + 2)] for n in range(N)]
    an.sort()
    for a in range(K + 2):
        if a == 0:
            continue
        elif a <= an[0]:
            dp[0][a] = (dp[0][a - 1] + 1) % mod
    for n in range(1,N):
        for k in range(1,K + 2):
            if k - an[n] <= 0:
                dp[n][k] = (dp[n - 1][k] + dp[n][k - 1]) % mod
            else:
                dp[n][k] =  dp[n][k-1] + (dp[n - 1][k] - dp[n - 1][k - an[n]]) % mod
    print(dp)

#M
#N
# O
# P
# Q
# R
# S
# T
# U
# V
# W
# X
# Y
# Z

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


s=list(input())
t=list(input())
dp=[[0 for i in range(len(t)+1)] for j in range(len(s)+1)]
for i in range(len(s)):
    for j in range(len(t)):
        if s[i]==t[j]:
            dp[i+1][j+1]=max(dp[i][j]+1,dp[i+1][j+1])
        dp[i][j+1]=max(dp[i][j],dp[i][j+1])
        dp[i+1][j]=max(dp[i][j],dp[i+1][j])
ans=[]
i=len(s)
j=len(t)
while(i>0 and j>0):
    if dp[i][j]==dp[i-1][j]:
        i-=1
    elif dp[i][j]==dp[i][j-1]:
        j-=1
    else:
        ans.append(s[i-1])
        i-=1
        j-=1
print("".join(ans[::-1]))


# https://atcoder.jp/contests/dp/tasks/dp_f
import sys
input = sys.stdin.readline

s = input()
t = input()

dp = [[''] * len(t) for _ in range(len(s))]

for i in range(1, len(s)):
    for j in range(1, len(t)):
        res = []
        if s[i - 1] == t[j - 1]:
            dp[i][j] = max(dp[i][j],
                           dp[i - 1][j - 1] + s[i - 1],
                           key=len)
        dp[i][j] = max(dp[i][j], dp[i][j - 1], key=len)
        dp[i][j] = max(dp[i][j], dp[i - 1][j], key=len)

print(dp[len(s) - 1][len(t) - 1])


S = input()
T = input()
LS = len(S); LT = len(T)

dp = [[-1]*(LT+1) for i in range(LS+1)]
nxt = [[(0, None, None)]*(LT+1) for i in range(LS+1)]
P = [[None]*(LT+1) for i in range(LS+1)]
Q = [[None]*(LT+1) for i in range(LS+1)]
R = [[0]*(LT+1) for i in range(LS+1)]
for i in range(LS-1, -1, -1):
    for j in range(LT-1, -1, -1):
        r0 = dp[i+1][j]; r1 = dp[i][j+1]
        r = max(r0, r1)
        if r0 < r1:
            rr = 0; p0 = i; q0 = j+1
        else:
            rr = 0; p0 = i+1; q0 = j
        if S[i] == T[j]:
            r2 = dp[i+1][j+1] + 1
            if r < r2:
                r = r2
                rr = 1; p0 = i+1; q0 = j+1
        dp[i][j] = r
        R[i][j] = rr
        P[i][j] = p0; Q[i][j] = q0

i = j = 0
ans = []
while i is not None:
    if R[i][j]:
        ans.append(S[i])
    i, j = P[i][j], Q[i][j]
print(*ans, sep='')


Score : 100 points

Problem Statement

In some other world, today is December D-th.

Write a program that prints Christmas if D = 25, Christmas Eve if D = 24, Christmas Eve Eve if D = 23 and Christmas Eve Eve Eve if D = 22.

Constraints

22 \leq D \leq 25

D is an integer.

Input

Input is given from Standard Input in the following format:

D

Output

Print the specified string (case-sensitive).

Sample Input 1

25

Sample Output 1

Christmas

Sample Input 2

22

Sample Output 2

Christmas Eve Eve Eve

Be sure to print spaces between the words.


a = int(input())
b = 25 - a
print('Christmas'+'Eve'*b)


d = int(input())

print("Christmas"+"Eve"*(25-d))


n = int(input())
s = "Christmas"

a = 25 - n
  s += " Eve" * a

print(s)


D = int(input())
DE = abs(25 - D)

print("Christmas" + " Eve" * DE)


D=int(input())
if D==25:
  print("Christmas")
else:
  if D==24:
    print("Christmas Eve")
  else:
    if D==23:
      print("Christmas Eve Eve")
    else:
      print("Christmas Eve Eve Eve")


d=int(input())

if d==22:
    c=" Eve Eve Eve"
elif d==23:
    c=" Eve Eve"
elif d==24:
    c=" Eve"
else:
    c=""
c="Christmas"+c

print(c)


if D=23:
    print('Christmas Eve Eve')

if D=24:
    print('Christmas Eve')

if D=23:
    print('Christmas ')


D = int(input())
if D == 25:
  print("Christmas")
elif D == 24:
  print("Christmas Eve")
elif D == 23:
  print("Christmas Eve Eve")
elif D == 22:
  print("Christmas Eve Eve Eve")


#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int mod = 1000000007;

int main() {
    ios::sync_with_stdio(false);
    int n, x[102] = {}, y[102] = {}, h[102] = {};
    cin >> n;
    for (int i = 0; i < n; i++) cin >> x[i] >> y[i] >> h[i];
    for (int i = 0; i <= 100; i++) {
        for (int j = 0; j <= 100; j++) {
            int a = abs(i - x[0]) + abs(j - y[0]) + h[0];
            bool w = 0;
            for (int k = 1; k < n; k++) {
                if (abs(i - x[k]) + abs(j - y[k]) + h[k] != a) w = 1;
            }
            if (w == 0) {
                cout << i << ' ' << j << ' ' << a << '\n';
                return 0;
            }
        }
    }
}

Score: 300 points

Problem Statement

In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.

The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0).

Aoki, an explorer, conducted a survey to identify the center coordinates and height of this pyramid. As a result, he obtained the following information:

C_X, C_Y was integers between 0 and 100 (inclusive), and H was an integer not less than 1.

Additionally, he obtained N pieces of information. The i-th of them is: "the altitude of point (x_i, y_i) is h_i."

This was enough to identify the center coordinates and the height of the pyramid. Find these values with the clues above.

Constraints

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

x_i and y_i are integers between 0 and 100 (inclusive).

h_i is an integer between 0 and 10^9 (inclusive).

The N coordinates (x_1, y_1), (x_2, y_2), (x_3, y_3), ..., (x_N, y_N) are all different.

The center coordinates and the height of the pyramid can be uniquely identified.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 h_1
x_2 y_2 h_2
x_3 y_3 h_3
:
x_N y_N h_N

Output

Print values C_X, C_Y and H representing the center coordinates and the height of the pyramid in one line, with spaces in between.

Sample Input 1

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

Sample Output 1

2 2 6

In this case, the center coordinates and the height can be identified as (2, 2) and 6.

Sample Input 2

2
0 0 100
1 1 98

Sample Output 2

0 0 100

In this case, the center coordinates and the height can be identified as (0, 0) and 100.

Note that C_X and C_Y are known to be integers between 0 and 100.

Sample Input 3

3
99 1 191
100 1 192
99 0 192

Sample Output 3

100 0 193

In this case, the center coordinates and the height can be identified as (100, 0) and 193.


n=int(input())
x=[-1]*n
y=[-1]*n
h=[-1]*n
for i in range(n):
  x[i],y[i],h[i]=map(int,input().split())

for cx in range(0,101):
  for cy in range(0,101):
    H=[]
    for i in range(n):
      if h[i]>0:
        H.append(h[i]+abs(cx-x[i])+abs(cy-y[i]))
    if len(set(H))==1:
      print(cx,cy,H[0])
      exit()


n = int(input())
dat = []
for _ in range(n):
    a,b,c = map(int,input().split())
    dat.append([a,b,c])
for x in range(101):
    for y in range(101):
        h = None
        can = True
        for i in range(n):
            xx, yy, hh = dat[i]
            canh = hh + abs(xx-x) + abs(yy-y)
            if h is not None:
                if canh != h:
                    can = False
            else:
                h = canh

        if can:
            break
    if can:
        break
print(x, y, h)


import sys
from collections import Counter
n = int(input())
x,y,h = [0]*n , [0]*n , [0]*n
q = 0
ze = 0

for i in range(n):
    x[i] ,y[i] ,h[i] = map(int,input().split())

ss = Counter(h)
if ss[0] >= n-1:
    ze = 1

for xx in range(101):
    for yy in range(101):
        fl = 1
        a = []
        for i in range(n):
            if h[i] != 0 or ze == 1:
                temp = abs(x[i]-xx) + abs(y[i]-yy) + h[i]
                a.append(temp)
                le = len(a)

                if le > 1:
                    if a[le-1] != a[le-2]:
                        fl = 0

        if fl == 1:
            print(xx,yy,max(a))
            sys.exit()


# coding: utf-8
# Your code here!
pyr=[[-1]*101 for i in range(101)]

N=int(input())

l=[]
for _ in range(N):
    x,y,h=map(int,input().split())
    l.append([x,y,h])

ans=0
for y in range(101):
    for x in range(101):
        for item in l:
            if item[2]==0:
                pass
            elif pyr[y][x]==-1:
                pyr[y][x]=item[2]+abs(item[0]-x)+abs(item[1]-y)
            elif pyr[y][x]!=item[2]+abs(item[0]-x)+abs(item[1]-y):
                pyr[y][x]=-100
            else:
                pass
        ans=max(ans,pyr[y][x])
        if ans==pyr[y][x]:
            temp=[x,y,ans]

print(*temp)


#!/usr/bin/env python3
import sys

def sample_index_not_zero_in_all_h(h):
    for i in range(len(h)):
        if h[i] != 0:
            return i

def solve(N: int, x: "List[int]", y: "List[int]", h: "List[int]"):
    h_isnot_zero = sample_index_not_zero_in_all_h(h)
    for cx in range(0, 101):
        for cy in range(0, 101):
            # 仮の頂点(Cx, Cy)の高さHを設定
            H_is_true = True
            H = h[h_isnot_zero] + abs(x[h_isnot_zero] - cx) + abs(y[h_isnot_zero] - cy)
            for i in range(N):
                if max(H - abs(x[i] - cx) - abs(y[i] - cy) , 0) != h[i]:
                    H_is_true = False
                    break
            if H_is_true == True:
                print(cx, cy, H)
                return

# Generated by 1.1.6 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
    x = [int()] * (N)  # type: "List[int]"
    y = [int()] * (N)  # type: "List[int]"
    h = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        x[i] = int(next(tokens))
        y[i] = int(next(tokens))
        h[i] = int(next(tokens))
    solve(N, x, y, h)

if __name__ == '__main__':
    main()


N = int(input())
l = []
for i in range(N):
    x, y, h = list(map(int, input().split(' ')))
    l.append((x, y, h))
if len(l) == 1:
    print('%d %d %d' % (l[0][0], l[0][1], l[0][2]))
    exit()
for cx in range(101):
    for cy in range(101):
        takasa = None
        correct = True
        for x, y, h in l:
            if h == 0:
                continue
            if takasa is None and h + (abs(cx - x) + abs(cy - y)) > 0:
                takasa = h + (abs(cx - x) + abs(cy - y))
            elif takasa != (h + (abs(cx - x) + abs(cy - y))):
                correct = False
                break
        if correct:
            print('%d %d %d' % (cx, cy, l[0][2] + abs(l[0][0] - cx) + abs(l[0][1] - cy)))


N = int(input())
info = [[int(i) for i in input().split()] for i in range(N)]
for i in range(N):
    if info[i][2] != 0:
        l = i
        break
for i in range(101):
    Cx= i
    for j in range(101):
        Cy = j
        h = info[l][2] + abs(info[l][0]-Cx) + abs(info[l][1]-Cy)
        for m in range(N):
            if info[m][2] != max(h-abs(info[m][0]-Cx)-abs(info[m][1]-Cy),0):
                break
            if m == N-1:
                print(str(i)+" "+str(j)+" "+str(h))


N = int(input())
XYHs = [list(map(int, input().split())) for _ in range(N)]

def height(i):
    return abs(XYHs[i][0] - cx) + abs(XYHs[i][1] - cy) + XYHs[i][2]

for cx in range(101):
    for cy in range(101):
        H = height(0)
        for i in range(1, N):
            if height(i) != H:
                sw = False
                break
        else:
            print("%d %d %d" % (cx, cy, H))
            s = True
            exit(1)


N = int(input())
xyh = [tuple(int(i) for i in input().split()) for i in range(N)]

def H(cx, cy, x, y, h):
    return h + abs(x - cx) + abs(y - cy)

def g(l, cx, cy):
    H_max_l = set(H(cx, cy, x, y, h) for x, y, h in xyh if h == 0)
    h_max = min(H_max_l) if any(H_max_l) else 10**9

    TH = set(H(cx, cy, x, y, h) for x, y, h in l if h > 0)
    if len(TH) == 1:
        high = TH.pop()
        if high <= h_max:
            return high
    return -1

def f(l):
    for cx in range(0, 101):
        for cy in range(0, 101):
            h = g(l, cx, cy)
            if h > 0:
                return cx, cy, h

cx, cy, h = f(xyh)
print(cx, cy, h)


from collections import defaultdict

def main():
    N = int(input())
    pairs = []
    for _ in range(N):
        pair = [int(e) for e in input().split()]
        pairs.append(pair)
    print(pairs)

    d = defaultdict(int)
    for pair in pairs:
        x, y, h = pair

        for X in range(101):
            for Y in range(101):
                H = h + (abs(X - x) + abs(Y - y))
                d[(X, Y, H)] += 1

    for k, v in d.items():
        if v == N:
            X, Y, H = k
            print(X, Y, H)

if __name__ == '__main__':
    main()


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

for i in range(101):
    for j in range(101):
        height = -1
        for x, y, h in XYH:
            hi = abs(x - i) + abs(y - j) + h
            if height == -1:
                height = hi
            else:
                if height == hi:
                    pass
                else:
                    break
        else:
            print(i, j, height)
            exit()


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

max_num = str(max(lis))
lis.pop(lis.index(int(max_num)))

if lis[0] > lis[1]:
    result = int(max_num + str(lis[0])) + lis[1]
else:
    result = int(max_num + str(lis[1])) + lis[0]

print(result)

Score : 100 points

Problem Statement

You have decided to give an allowance to your child depending on the outcome of the game that he will play now.

The game is played as follows:

There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a + printed on it.

The player should construct a formula of the form X + Y, by arranging the four panels from left to right. (The operator panel should not be placed at either end of the formula.)

Then, the amount of the allowance will be equal to the resulting value of the formula.

Given the values A, B and C printed on the integer panels used in the game, find the maximum possible amount of the allowance.

Constraints

All values in input are integers.

1 \leq A, B, C \leq 9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum possible amount of the allowance.

Sample Input 1

1 5 2

Sample Output 1

53

The amount of the allowance will be 53 when the panels are arranged as 52+1, and this is the maximum possible amount.

Sample Input 2

9 9 9

Sample Output 2

108

Sample Input 3

6 6 7

Sample Output 3

82


a = list(map(int, input().split()))
a.sort(reverse=True)
print(int(str(a[0]) + str(a[1])) + a[2])


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


a = list(map(int, input().split()))
a = sorted(a)
b = [str(a[2]), str(a[1])]
c = ''.join(b)
print(int(c) + a[0])


A= list(map(int, input().split()))
B= sorted(A,reverse=True)
print(B[0]*10+B[1]+B[2])


# coding: utf-8
# Your code here!

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

abc.sort(reverse=True)

# print(abc)

# print(abc[0])
# print(abc[1])
# print(abc[2])

print(((abc[0] * 10) + (abc[1])) + abc[2])


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

print(a[-1] * 10 + a[0] + a[1])


N, M, X, Y = map(int, input().split())
x = max(list(map(int, input().split())))
y = min(list(map(int, input().split())))
print('No War' if x < y and X < y else 'War')

Score : 200 points

Problem Statement

Our world is one-dimensional, and ruled by two empires called Empire A and Empire B.

The capital of Empire A is located at coordinate X, and that of Empire B is located at coordinate Y.

One day, Empire A becomes inclined to put the cities at coordinates x_1, x_2, ..., x_N under its control, and Empire B becomes inclined to put the cities at coordinates y_1, y_2, ..., y_M under its control.

If there exists an integer Z that satisfies all of the following three conditions, they will come to an agreement, but otherwise war will break out.

X < Z \leq Y

x_1, x_2, ..., x_N < Z

y_1, y_2, ..., y_M \geq Z

Determine if war will break out.

Constraints

All values in input are integers.

1 \leq N, M \leq 100

-100 \leq X < Y \leq 100

-100 \leq x_i, y_i \leq 100

x_1, x_2, ..., x_N \neq X

x_i are all different.

y_1, y_2, ..., y_M \neq Y

y_i are all different.

Input

Input is given from Standard Input in the following format:

N M X Y
x_1 x_2 ... x_N
y_1 y_2 ... y_M

Output

If war will break out, print War; otherwise, print No War.

Sample Input 1

3 2 10 20
8 15 13
16 22

Sample Output 1

No War

The choice Z = 16 satisfies all of the three conditions as follows, thus they will come to an agreement.

X = 10 < 16 \leq 20 = Y

8, 15, 13 < 16

16, 22 \geq 16

Sample Input 2

4 2 -48 -1
-20 -35 -91 -23
-22 66

Sample Output 2

War

Sample Input 3

5 3 6 8
-10 3 1 5 -100
100 6 14

Sample Output 3

War


N,M,X,Y=map(int, input().split())
Xpoints=list(map(int, input().split()))
Ypoints=list(map(int, input().split()))

for z in range(-100, 101):
    if X < z and z <= Y:
        if max(Xpoints) < z:
            if min(Ypoints) >= z:
                print('No War')
else:
    print('War')


m, n, x, y = map(int, input().split())
xs = list(map(int, input().split()))
ys = list(map(int, input().split()))

ans = 'No War'
if not (x < y):
    ans = 'War'
if not (max(xs) < min(ys)):
    ans = 'War'

print(ans)


n, m, x, y = map(int, input().split())
xn = map(int, input().split())
ym = map(int, input().split())

if max(x, max(xn)) < min(y, min(ym)):
    print("No War")
else:
    print("War")


n, m, x, y = map(int, input().split())
xs = list(map(int, input().split()))
ys = list(map(int, input().split()))
if x < y and x < min(ys) and max(xs) <= y and max(xs) <= min(ys):
    print('No War')
else:
    print('War')


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

data_x = list(map(int,input().split()))
data_y = list(map(int,input().split()))

max_x = max(data_x)
min_y = min(data_y)

if  max_x > min_y:
	print('War')
elif data_x.count(Y) != 0:
    print('War')
elif data_y.count(X) != 0:
    print('War')
else:
    print('No War')


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

b = input().split()
b = [int(i) for i in b]

c = input().split()
c = [int(i) for i in c]

maxb = max(b)
minc = min(c)

if maxb < minc and a[2] < a[3] and maxb < a[3] and minc > a[2]:
	print ('No War')
else:
	print ('War')


a, b=map(int, input().split())
if (a*b)%2==0:
  print('No')
else:
  print('Yes')

Score : 100 points

Problem Statement

You are given integers A and B, each between 1 and 3 (inclusive).

Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number.

Constraints

All values in input are integers.

1 \leq A, B \leq 3

Input

Input is given from Standard Input in the following format:

A B

Output

If there is an integer C between 1 and 3 that satisfies the condition, print Yes; otherwise, print No.

Sample Input 1

3 1

Sample Output 1

Yes

Let C = 3. Then, A \times B \times C = 3 \times 1 \times 3 = 9, which is an odd number.

Sample Input 2

1 2

Sample Output 2

No

Sample Input 3

2 2

Sample Output 3

No


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

if(A%2!=0 and B%2!=0):
  print("Yes")
else:
  print("No")


a,b = map(int,input().split())
if a % 2 == 0 or b%2==0:
    print("No")
else:
    print("Yes")


from math import gcd
import functools

if __name__ == '__main__' :
    N,X = map(int, input().split())
    x = list(map(int, input().split()))

    dist_list = [abs(d-X) for d in x]

    print(functools.reduce(gcd, dist_list))


from collections import Counter

n=int(input())
l=[input() for i in range(n)]

if Counter(l).most_common()[0][1] != 1:
  ans="No"
else:
  l_head = [l[i+1][0] for i in range(n-1)]
  l_tail = [l[i][-1] for i in range(n-1)]
  if l_head == l_tail:
    ans="Yes"
  else:
    ans="No"

print(ans)

Score : 200 points

Problem Statement

Takahashi is practicing shiritori alone again today.

Shiritori is a game as follows:

In the first turn, a player announces any one word.

In the subsequent turns, a player announces a word that satisfies the following conditions:

That word is not announced before.

The first character of that word is the same as the last character of the last word announced.

In this game, he is practicing to announce as many words as possible in ten seconds.

You are given the number of words Takahashi announced, N, and the i-th word he announced, W_i, for each i. Determine if the rules of shiritori was observed, that is, every word announced by him satisfied the conditions.

Constraints

N is an integer satisfying 2 \leq N \leq 100.

W_i is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
W_1
W_2
:
W_N

Output

If every word announced by Takahashi satisfied the conditions, print Yes; otherwise, print No.

Sample Input 1

4
hoge
english
hoge
enigma

Sample Output 1

No

As hoge is announced multiple times, the rules of shiritori was not observed.

Sample Input 2

9
basic
c
cpp
php
python
nadesico
ocaml
lua
assembly

Sample Output 2

Yes

Sample Input 3

8
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaa
aaaaaaa

Sample Output 3

No

Sample Input 4

3
abc
arc
agc

Sample Output 4

No


# solution
import io

n = int(input())
m = [input() for _ in range(n)]

report = 'Yes'
if n!=len(set(m)):
  report ='No'
else:
  for i in range(n-1):
    if m[i][-1]!=m[i+1][0]:
      report='No'
      break
print(report)


N = int(input())

appeared = []
prev = input()
for i in range(N-1):
    appeared += [prev]
    S = input()
    if prev[-1] != S[0] or S in appeared:
        print('No')
        exit()
    prev = S
print('Yes')


n, x = map(int, input().split())
x_s = list(map(int, input().split()))

x_s.append(x)
x_s.sort()
sub = []
for i in range(n):
    sub.append(x_s[i+1]-x_s[i])

print(min(sub))

Score : 300 points

Problem Statement

There are N cities on a number line. The i-th city is located at coordinate x_i.

Your objective is to visit all these cities at least once.

In order to do so, you will first set a positive integer D.

Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like:

Move 1: travel from coordinate y to coordinate y + D.

Move 2: travel from coordinate y to coordinate y - D.

Find the maximum value of D that enables you to visit all the cities.

Here, to visit a city is to travel to the coordinate where that city is located.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq X \leq 10^9

1 \leq x_i \leq 10^9

x_i are all different.

x_1, x_2, ..., x_N \neq X

Input

Input is given from Standard Input in the following format:

N X
x_1 x_2 ... x_N

Output

Print the maximum value of D that enables you to visit all the cities.

Sample Input 1

3 3
1 7 11

Sample Output 1

2

Setting D = 2 enables you to visit all the cities as follows, and this is the maximum value of such D.

Perform Move 2 to travel to coordinate 1.

Perform Move 1 to travel to coordinate 3.

Perform Move 1 to travel to coordinate 5.

Perform Move 1 to travel to coordinate 7.

Perform Move 1 to travel to coordinate 9.

Perform Move 1 to travel to coordinate 11.

Sample Input 2

3 81
33 105 57

Sample Output 2

24

Sample Input 3

1 1
1000000000

Sample Output 3

999999999


n,x=map(int, input().split())
x_list=list(map(int, input().split()))
x_list.sort()

from fractions import gcd

ans=abs(x-x_list[0])
for i in range(1, n):
    x_diff=x_list[i]-x_list[i-1]
    ans=gcd(ans, x_diff)

print(ans)


import fractions
from functools import reduce

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

N , X = map(int, input().split())
x = list(map(int, input().split()))
d = []

for i in range(N):
    d.append(abs(x[i] - X))

ans = gcd_list(d)
print(ans)


import fractions
N, X = map(int, input().split())
x = list(map(int, input().split()))
tmp = abs(x[0] - X)
for i in range(1,N):
  tmp = fractions.gcd(tmp,abs(x[i]-X))
print(tmp)


n, X = map(int, input().split())
x = list(map(int, input().split()))
x.append(X)
x = sorted(x)
y = [x[i+1]-x[i] for i in range(n)]

def eu(a, b):
    a, b = sorted([a,b])
    while a != 0:
        b, a = a, b%a
    return b
d = y[0]
for i in range(1, n-1):
    d = eu(d, y[i])
print(d)


import numpy as np

def q74(N, X, x):
    y = np.array(x)
    return min(abs(y - X))

N, X= [int(i) for i in input().split()]
x = [int(i) for i in input().split()]

print(q74(N, X, x))


from fractions import gcd
from functools import reduce
N, X = map(int, input().split())
x = [abs(X - int(i)) for i in input().split()]
x.sort(reverse=True)
print(reduce(gcd, x))


import math

N, S = [int(x) for x in input().split()]
X = [int(x) for x in input().split()]

A = [x - S for x in X]

def lcd(a,b):
    a = abs(a)
    b = abs(b)
    a,b = min(a,b), max(a,b)
    if a == 0:
        return b
    return lcd(b%a, a)

ret = A[0]
for a in A:
    ret = lcd(ret, a)

print(ret)


import numpy as np
def div(N):
    sq = int(np.sqrt(N))
    divs = [1]
    for i in range(2,sq+1):
        if  N%i == 0:
            divs.append(i)
    divs.append(N)
    return divs

N,S = map(int, input().split())
X = list(map(int,input().split()))

X.append(S)
X = sorted(X)

X_del = []
for i in range(N):
    X_del.append(X[i+1] - X[i])

min_del = min(X_del)
ans = 1

np_X_del = np.array(X_del)
divs = div(min_del)

for div in divs[::-1]:
    sa = abs(np_X_del - div)
    if np.min(sa) >= 0:
        waru = np_X_del % div

        if np.max(waru) == 0:
            print(div)
            exit()


import numpy as np

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

line = input().split()
N = int(line[0])
X = int(line[1])

line = input().split()

diff = [abs(int(x)-X) for x in line]

min_ = gcd(diff[0], diff[0])

for df in diff:
    min_ = min(min_, gcd(diff[0], df))

print(min_)


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

cnt = 0
for i in range(1, 100**3+1):
    if i % 100 ** d == 0:
        cnt += 1
    if cnt == n:
        print(i)
        exit()

Score: 200 points

Problem Statement

Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.

As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.

Find the N-th smallest integer that would make Ringo happy.

Constraints

D is 0, 1 or 2.

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

Input

Input is given from Standard Input in the following format:

D N

Output

Print the N-th smallest integer that can be divided by 100 exactly D times.

Sample Input 1

0 5

Sample Output 1

5

The integers that can be divided by 100 exactly 0 times (that is, not divisible by 100) are as follows: 1, 2, 3, 4, 5, 6, 7, ...

Thus, the 5-th smallest integer that would make Ringo happy is 5.

Sample Input 2

1 11

Sample Output 2

1100

The integers that can be divided by 100 exactly once are as follows: 100, 200, 300, 400, 500, 600, 700, 800, 900, 1 \ 000, 1 \ 100, ...

Thus, the integer we are seeking is 1 \ 100.

Sample Input 3

2 85

Sample Output 3

850000

The integers that can be divided by 100 exactly twice are as follows: 10 \ 000, 20 \ 000, 30 \ 000, ...

Thus, the integer we are seeking is 850 \ 000.


import math
import string

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

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

def has_duplicates2(seq):
    seen = []
    for item in seq:
        if not(item in seen):
            seen.append(item)
    return len(seq) != len(seen)

def divisor(n):
    divisor = []
    for i in range(1, n+1):
        if n % i == 0:
            divisor.append(i)
    return divisor

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

def func(x):
    cnt = 0
    while x % 100 == 0:
        cnt += 1
        x /= 100
    return cnt == d

a = []

for i in range(1, 10000000):
    if func(i):
        a.append(i)
print(a[n-1])


from itertools import accumulate, permutations, combinations, product, combinations_with_replacement
from math import floor, ceil, sqrt, factorial, log
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict
from heapq import heappop, heappush, heappushpop
from itertools import product
import sys
stdin = sys.stdin
mod = 10**9 + 7

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

def ni(): return int(ns())

def na(): return list(map(int, stdin.readline().split()))

D, N = na()
if D == 0:
    print(N)
elif D == 1:
    print(N * 100**D if N != 100 else 101 * 100**D)
else:
    print(N * 100**D)


A = list(map(int,input().split()))
a = A[0]
b = A[1]
a = 100**a
s = a*b
print(int(s))


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

if D == 0:
    A = N
elif D == 1:
    A = N * 100
else:
    A = N * 10000

print(A)


import sys
sys.setrecursionlimit(200000)
input = sys.stdin.readline

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

def f(n):
    if n % 100 == 0:
        return f(n // 100) + 1
    else:
        return 0

c = 0
for i in range(1, 2000001):
    if A == f(i):
        c += 1

    if c == B:
        print(i)
        exit()


import sys
sys.setrecursionlimit(200000)
input = sys.stdin.readline

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

print(100 ** A * B)


import os, sys, re, math

D,N = map(int,input().split(' '))
ret = (100 ** D) * N
if N == 100:
    ret += 100 ** D
print(ret)


d,n = map(int,input().split())
print([i*100**d for i in range(101)][n])


d, n = map(int, input().split())
if n != 100:
    print(n*100**d)
else:
    print((n+1)*10**d)


# coding: utf-8
import sys
input = sys.stdin.readline

D, N = map(int, input().split())
if N == 100:
    print(pow(100, D) * 101)
else:
    print(pow(100, D) * N)


d, n = list(map(int, input().split()))
print(n * (100**d))


d, n = map(int,input().split())
if n != 100:
    print(100 ** d * n)
else:
    print(100 ** d * n + 1)


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

if D == 0:
    print(N)
elif D == 1:
    print(N*100)
elif D == 2:
    print(N*10000)


D, N = list(map(int, input().split()))
if N != 100:
    print(100**D*N)
else:
    print(100**D*101)


import sys
input = sys.stdin.readline
A = int(input())
B = int(input())
C = int(input())
X = int(input())
ans = 0
for i in range(A + 1):
    x = 500 * i
    if x == X:
        ans += 1
        break
    elif x > X:
        break
    for j in range(B + 1):
        x = 500 * i + 100 * j
        if x == X:
            ans += 1
            break
        elif x > X:
            break
        for k in range(C + 1):
            x = 500 * i + 100 * j + 50 * k
            if x == X:
                ans += 1
print(ans)

Score : 200 points

Problem Statement

You have A 500-yen coins, B 100-yen coins and C 50-yen coins (yen is the currency of Japan).
In how many ways can we select some of these coins so that they are X yen in total?

Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that coin are different.

Constraints

0 \leq A, B, C \leq 50

A + B + C \geq 1

50 \leq X \leq 20 000

A, B and C are integers.

X is a multiple of 50.

Input

Input is given from Standard Input in the following format:

A
B
C
X

Output

Print the number of ways to select coins.

Sample Input 1

2
2
2
100

Sample Output 1

2

There are two ways to satisfy the condition:

Select zero 500-yen coins, one 100-yen coin and zero 50-yen coins.

Select zero 500-yen coins, zero 100-yen coins and two 50-yen coins.

Sample Input 2

5
1
0
150

Sample Output 2

0

Note that the total must be exactly X yen.

Sample Input 3

30
40
50
6000

Sample Output 3

213


a=int(input())
b=int(input())
c=int(input())
x=int(input())

count=0
for i in range(a+1):
    for j in range(b+1):
        for k in range(c+1):
            d=500*i+100*j+50*k
            if d == x:
                count +=1

print(count)


a = int(input())
b = int(input())
c = int(input())
x = int(input())
cnt = 0

for i in range(a+1):
    for j in range(b+1):
        for k in range(c+1):
            if(500*i+100*j+50*k == x):
                cnt+=1

print(cnt)


a = int(input())
b = int(input())
c = int(input())
x = int(input())
count = 0
for aa in range(a+1):
    ay = 500*aa
    if ay <= x:
        for bb in range(b+1):
            by = 100*bb
            if ay + by <= x:
                for cc in range(c+1):
                    cy = 50*cc
                    if ay + by + cy ==x:
                        count += 1
                        break
print(count)


list_500 = list(range(A+1))
list_100 = list(range(B+1))
list_50 = list(range(C+1))

for fh in range(len(list_500)):
    for oh in range(len(list_100)):
      for f in range(len(list_50)):
        if list_500[fh] * 500 + list_100[oh] * 100 + list_50[f] * 50 == X:
          counter += 1

print(counter)


import re  # 正規表現, findall('正規表現', 文字列), search('正規表現', 文字列)
import sys # プログラム終了：sys.exit()
# sys.setrecursionlimit(10**6) # 再帰呼び出しの上限を上げる

def i_input(): return int(input())
def s_input(): return map(int,input().split())
def l_input(): return list(map(int, input().split()))
# 文字列のまま受け取りたいときはinput()

def check(x, a, b, c):
    diff = x - 500 * a - 100 * b
    if diff >= 0 and diff % 50 == 0 and diff // 50 <= c:
        print(a,b,diff // 50)
        return True
    else:
        return False

def main():
    a = i_input() # 500
    b = i_input() # 100
    c = i_input() # 50
    x = i_input() # sum

    count = 0
    for i in range(a + 1):
        for j in range(b + 1):
            if check(x, i, j, c):
                count += 1

    print(count)

if __name__ == "__main__":
    main()


if __name__ == '__main__':
    a = int(input())
    b = int(input())
    c = int(input())
    x = int(input())

    count = 0
    for ia in range(a+1):
        for ib in range(b+1):
            for ic in range(c+1):
                if 500*ia+100*ib+50*ic == x:
                    count = count+1

    print(count)


A=int(input())
B=int(input())
C=int(input())
total=int(input())
count=0
for a in [a*500 for a in range(A+1)]:
    for b in [b*100 for b in range(B+1)]:
        for c in [c*50 for c in range(C+1)]:
            if a+b+c==0:
                break
            if a+b+c==total:
                count+=1
print(count)


A = int(input())
B = int(input())
C = int(input())
X = int(input())

count = 0

for a in range(A+1):
    for b in range(B+1):
        for c in range(C+1):
            if (a*500 + b*100 + c*50) == X:
                count += 1
print(count)


# スペース区切りの整数の入力
b, c = map(int, input().split())

if b * c % 2 == 0:
  print("Even")
else:
  print("Odd")

Score : 100 points

Problem Statement

AtCoDeer the deer found two positive integers, a and b.
Determine whether the product of a and b is even or odd.

Constraints

1 ≤ a,b ≤ 10000

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If the product is odd, print Odd; if it is even, print Even.

Sample Input 1

3 4

Sample Output 1

Even

As 3 × 4 = 12 is even, print Even.

Sample Input 2

1 21

Sample Output 2

Odd

As 1 × 21 = 21 is odd, print Odd.


a, b = map(int, input().split())
if (a*b)%2 == 0:
  print("Even")
else:
  print("Odd")


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

if a % 2 != 0 and b % 2 != 0:
    print('0dd')
else:
    print('Even')


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

c=a*b

c=int(c)

if c%2==0:
    print("Even")

if else:
    print("Odd")


a, b = map(int, input().split())
if (a*b) % 2:
  print("Odd")
else:
  print("Even")


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

if a * b % 2 == 0:
    print("Odd")
else:
    print("Even")


a,b = (int(i) for i in input().split())

c = a * b
if c % 2 == 0:
    print('Even')
else:
    print('Odd')


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

if ((a * b) % 2) == 0:
	print('Even')
else:
	print('Odd')


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

if a*b%2 == 0:
  print('Even')
else:
  print('0dd')


a,b=map(int,input().split())
print("Odd" if a*b%2!=0 else "Even")


a = input()
a, b = a.split()
c = int(a)*int(b)
if ((c % 2) == 0) :
  print("Even")
else:
  print("Odd")


a,b=map(int,input().split())
x=a*b
if x%2 == 0:
  print("Odd")
else:
  print("Even")


a, b = map(int, input().split())
if (a*b) % 2 == 1:
    print("Odd")
else:
    print("Even")


a,b,c=map(int, input().split())
if (a*b)%2==0:
  print('Even')
esle:
  print('0dd')


a,b = map(int,input().split())
if a*b %2 == 0:
    print("Even")
else:
    print("Odd"
          )


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

print("Odd" if a * b % 2 else "Even")


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

if int(b) % 2 == 0 or int(c) % 2 == 0:
    print('Even')

else:
    print('Odd')


a,b=map(int, input().split())
x=a*b
if x%2==0:
    print("Even")
else :
    print("Odd")


a, b = map(int,input().split())
if a * b % 2 == 0:
  print("Even")
elif
  print("Odd")


answer = "Odd"
if a*b%2 == 0:
  answer = "Even"
print(answer)


a, b = [int(i) for i in input().split()]
if (a*b) & 1:
   print('Odd')
else :
   print('Even')


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

x = a*b

if x%2 == 0:
    print('Even')
else:
    print('Odd')


if __name__ == "__main__":
    a, b = map(int, input().split())
    if a * b % 2 == 0:
        print ("Even")
    else:
        print ("Odd")


def otoshidama(N,Y):
  ansi, ansj, ansk = -1, -1, -1
  if Y/10000 > N:
    return ansi, ansj, ansk
  for i in range(N+1):
    for j in range(N+1-i):
      k = N - i - j
      if i*1000 + j*5000 + k*10000 == Y:
        ansi, ansj, ansk = i, j, k
        return ansi,ansj,ansk
  return ansi,ansj,ansk
N,Y = [int(i) for i in input().split()]
ansi, ansj, ansk = otoshidama(N,Y)
print(ansk, ansj, ansi)

Score : 300 points

Problem Statement

The commonly used bills in Japan are 10000-yen, 5000-yen and 1000-yen bills. Below, the word "bill" refers to only these.

According to Aohashi, he received an otoshidama (New Year money gift) envelope from his grandfather that contained N bills for a total of Y yen, but he may be lying. Determine whether such a situation is possible, and if it is, find a possible set of bills contained in the envelope. Assume that his grandfather is rich enough, and the envelope was large enough.

Constraints

1 ≤ N ≤ 2000

1000 ≤ Y ≤ 2 × 10^7

N is an integer.

Y is a multiple of 1000.

Input

Input is given from Standard Input in the following format:

N Y

Output

If the total value of N bills cannot be Y yen, print -1 -1 -1.

If the total value of N bills can be Y yen, let one such set of bills be "x 10000-yen bills, y 5000-yen bills and z 1000-yen bills", and print x, y, z with spaces in between. If there are multiple possibilities, any of them may be printed.

Sample Input 1

9 45000

Sample Output 1

4 0 5

If the envelope contained 4 10000-yen bills and 5 1000-yen bills, he had 9 bills and 45000 yen in total. It is also possible that the envelope contained 9 5000-yen bills, so the output 0 9 0 is also correct.

Sample Input 2

20 196000

Sample Output 2

-1 -1 -1

When the envelope contained 20 bills in total, the total value would be 200000 yen if all the bills were 10000-yen bills, and would be at most 195000 yen otherwise, so it would never be 196000 yen.

Sample Input 3

1000 1234000

Sample Output 3

14 27 959

There are also many other possibilities.

Sample Input 4

2000 20000000

Sample Output 4

2000 0 0


n,y = map(int,input().split())
y //= 1000
f = 0
for s in range(n+1):
    for t in range(n+1-s):
        if s+t*5+(n-s-t)*10 == y:
            f = 1
            print(n-s-t,t,s)
            break
    if f == 1:
        break
else:
    print(-1,-1,-1)


def solve(args):
    n, y = args
    #.
    y = y // 1000

    #.
    for i in range(n+1):
        for j in range(n+1):
            #.
            money = y - i*10 - j*50

            #.
            if money == n - i - j:
                return "{} {} {}".format(i, j, money)

    return "-1 -1 -1"

print(solve(map(int, input().split())))


N,Y = map(int,input().split())
a,b,c = N+1,N+1,N+1
dama = 0
count = 0

if Y // N == 10000:
    print(N,0,0)
elif Y // N == 5000:
    print(0,N,0)
elif Y // N == 1000:
    print(0,0,N)
else:
    stop = False
    for i in range(a):
        if stop:
            break
        b -= i
        for j in range(b):
            if stop:
                break
            c -= i+j
            if i+j+c != N:
                pass
            else:
                dama = 10000*i + 5000*j + 1000*c
                if dama == Y:
                    print(i,j,c)
                    count += 1
                    stop = True
                    break
            c = N
        b = N+1
    if count == 0:
        print(-1,-1,-1)


#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
  int N, Y;
  cin >> N >> Y;
  bool flag = false;
  int res10000 = -1;
  int res5000 = -1;
  int res1000 = -1;
  for (int i = 0; i <= N; i++) {
  	for (int j = 0; j <= N; j++) {
      int k = N - i - j;
      if (i + j <= N && 10000 * i + 5000 * j + 1000 * k == Y) {
        flag = true;
        res10000 = i;
        res5000 = j;
        res1000 = k;
      }
      if (flag) break;
    }
    if (flag) break;
  }

  cout << res10000 << " " << res5000 << " " << res1000 << endl;
}


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

for x in range(n+1):
    for y in range(n+1-x):
        tmp = n-x-y
        if (x*10000+y*5000+tmp*1000) == s:
            print('{} {} {}'.format(x,y,tmp))
            exit(0)

print('-1 -1 -1')


N, Y = map(int, input().split())
ans = -1,-1,-1
for x in range(N+1):
    for y in range(N - x + 1):
        z = N - x - y
        if 0<=z<=2000 and 10000*x+5000*y+1000*z == Y:
            ans = x,y,z
            break
    else:
        continue
    break
print(*ans)


n,y = map(int,input().split())
y //= 1000
m = [10,5,1]
count = [0,0,0]
for i in range(3):
    count[i] = y//m[i]
    y %= m[i]
if sum(count) <= n:
    print(count[0],count[1],count[2])
else:
    print(-1,-1,-1)


n,y = map(int,input().split())
y //= 1000
m = [10,5,1]
count = [0,0,0]
for i in range(3):
    count[i] = y//m[i]
    y %= m[i]
if sum(count) < n:
    print(" ".join(map(str,count)))
    print()
else:
    print(-1,-1,-1)


# -*- coding: utf-8 -*-
# スペース区切りの整数の入力
N, Y = map(int, input().split())
# 文字列の入力
#s = input()
#print(s[0:K-1]+s[K-1].lower()+s[K:N])

i=0
j=0
k=0

ans="-1 -1 -1"
sum=0

for i in range(N+1):
    for j in range(N-i+1):
        k=N-i-j
        sum = 10000*i + 5000*j + 1000*k
        if sum==Y:
            ans = str(i) + " " + str(j) + " " + str(k)
            break

print(ans)


import numpy as np
if __name__ == "__main__":
    N, Y = map(int, input().split())
    ans = [-1, -1, -1]
    for i in range(N+1):
        for j in range(N+1-i):
            k = N - i - j
            y = 10000 * i + 5000 * j + 1000 * k
            if y == Y:
                ans = [i, j, k]
    print("{} {} {}".format(ans[0], ans[1], ans[2]))


import sys
f = 1
n,y = map(int,input().split())
for s in range(2001):
    for t in range(2001):
        z = n-s-t
        if y-(10000*s+5000*t+1000*z) == 0 and z >= 0 :
            print(s,t,z)
            f = 0
            sys.exit()
if f == 1:
    print(-1,-1,-1)


#ABC 085C
import sys
f = 1
n,y = map(int,input().split())
for s in range(2001):
    for t in range(2001):
        for z in range(2001):
            if y-(10000*s+5000*t+1000*z) == 0 and s+t+z == n  :
                print(s,t,z)
                f = 0
                sys.exit()
if f == 1:
    print(-1,-1,-1)


import sys
n, y = map(int, input().split())

for i in range(n):
    for j in range(n - i):
        k = n - i - j
        if 10000 * i + 5000 * j + 1000 * k == y:
            print(i, j, k)
            sys.exit()

print('-1, -1, -1')


n, y = map(int, input().split())
for a in range(n):
  for b in range(n):
    c = n - a - b
    if c < 0:
      continue
    if 10000*a + 5000*b + 1000*c == y:
      print(a, b, c)
      exit()
else:
  print(-1, -1, -1)


n, y = list(map(int,input().split()))
flag = 0
for i in range(n+1):
    for j in range(n-i+1):
        if 10000*i + 5000*j + 1000*(n - i - j )==y:
            print(i, j, n-i-j)
            flag = 1
            break
    if flag == 1:
        break

if flag == 0:
    print(-1,-1,-1)


# -*- coding: utf-8 -*-
N , Y = map(int,input().split())
z = 0
for i in range(N+1):
    rest = Y - 10000 * i
    for j in range(N+1-i):
        if rest < 0:
            break
        rest1 = rest - (5000 * j) -(1000 * (N-i-j))
        if rest1 == 0:
            print(i, j, N-i-j)
            z = 1
        if z == 1:
            break
    if z == 1:
        break
if z == 0:
    print("-1 -1 -1")


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

k = 0

for i in range(n+1):
    if k != 0:
        break
    for j in range(n+1):
        x = i
        y = j
        z = n - (i+j)

        if z < 0:
            break

        if 10000*x + 5000*y + 1000*z == Y:
            print(x,y,z)
            k += 1
            break

if k == 0:
    print(-1,-1,-1)


N, Y = map(int, input().split())
Y = Y // 1000
for x in range(N + 1):
	for y in range(N + 1):
		if 10 * x + 5 * y + (N - x - y) == Y and 0 <= N - x - y <= N:
			print(x, y, N - x - y)
			exit()
print(-1, -1, -1)


N, Y = map(int, input().split())
l = []
flag = False
for i in range(N+1):
    for j in range(N-i+1):
        if 10000 * i + 5000 * j + 1000 * (N-i-j) == Y:
            l = [i, j, N-i-j]
            flag = True
        if flag:
            break
if flag:
    print(*l)
else:
    print(-1, -1, -1)


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

for x in range(N+1):
    for y in range(N+1):
        z = Y - x*10000 - y*5000
        if z < 0 or z % 1000 != 0:
            pass
        else:
            if x+y+int(z/1000) == N:
                print(x,y,int(z/1000))
                exit()

print(-1,-1,-1)


#入力
N, Y = map(int, input().split())

#総当たりで合計金額を算出
x = []
y = []
z = []

for num_ten_thousand in range(0, N+1):
    for num_five_thousand in range(0, N+1):

            #千円の枚数を算出
            num_one_thousand = N-(num_ten_thousand+num_five_thousand)

            #合計金額を算出
            total = num_ten_thousand*10000 + num_five_thousand*5000 + num_one_thousand*1000

            #（合計金額がYと等しいか・合計枚数がNと等しいか）を確認し答えをリストに格納
            if Y==total and N==num_ten_thousand+num_five_thousand+num_one_thousand:
                x.append(num_ten_thousand)
                y.append(num_five_thousand)
                z.append(num_one_thousand)

#答えを出力
if not x:
    print(-1, -1, -1, sep=" ")

else:
    print(x[0], y[0], z[0], sep=" ")


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

def greedy(Y):
    res = Y
    yukichi = 0
    ichiyo = 0
    hideyo = 0
    while res >= 10000:
        res -= 10000
        yukichi += 1

    while res >= 5000:
        res -= 5000
        ichiyo += 1

    while res > 0:
        res -= 1000
        hideyo += 1

    return yukichi, ichiyo, hideyo

def confirm_N(N,yukichi,ichiyo,hideyo):
    bill = yukichi+ichiyo+hideyo
    if N<bill:
        return [-1,-1,-1]
    elif N == bill:
        return [yukichi, ichiyo, hideyo]

    while yukichi >= 0:
        if bill == N:
            return [yukichi, ichiyo, hideyo]

        while ichiyo > 0:
            bill += 4
            hideyo += 5
            ichiyo -= 1
            if bill == N:
                return [yukichi, ichiyo, hideyo]

        bill += 1
        yukichi -= 1
        ichiyo = 2

    return [-1,-1,-1]

#1.まず貪欲

yukichi, ichiyo, hideyo = greedy(Y)

bill = yukichi+ichiyo+hideyo

ans_lst = confirm_N(N, yukichi, ichiyo, hideyo)

print(*ans_lst)


def calculate_money(array):
    return [i * j for (i, j) in zip(array, money_list)]

if __name__ == '__main__':
    input_list = input().split()
    N = int(input_list[0])
    Y = int(input_list[1])
    money_list = [10000, 5000, 1000]
    num_list = []

    for x_num in range(0, N + 1):
        for y_num in range(0, N + 1 - x_num):
            num_list.append([x_num, y_num, N - x_num - y_num])

    cal_list = list(map(calculate_money, num_list))

    result = []

    for num, cal in enumerate(cal_list):
        if sum(cal) == Y:
            result = num_list[num]

    if len(result) == 0:
        print("-1 -1 -1")
    else:
        print(" ".join(map(str, result)))


n, y = map(int, input().split())
x, y, z = -1, -1, -1
for i in range(n + 1):
    for j in range(n + 1 - i):
        for k in range(n + 1 - i - j):
            if 10000 * i + 5000 * j + 1000 * k == y:
                x, y, z = i, j, k
print(x, y, z)


n, y = input().split()
n = int(n)
y = int(y) // 1000

if y > 10 * n:
    print(-1,-1,-1)
elif y < n:
    print(-1,-1,-1)
else:
    flg = False

    for i in range(n+1):
        for j in range(n-i+1):
            k = n-i-j
            if y == i + 5 * j + 10 * k:
                print(k,j,i)
                flg = True
                break

    if flg == False:
        print(-1,-1,-1)