n, m = map(int, input().split())
ans = [0] * m

for _ in range(n):
    a = list(map(int, input().split()))
    for i in a[1:]:
        ans[i] += 1

print(ans.count(n))

n, m = map(int, input().split())
ans = [0] * m
for _ in range(n):
    a = list(map(int, input().split()))

    for i in a[1:]:
        ans[i - 1] += 1

print(ans.count(n))


N, M = map(int, input().split())
loved_by_everyone = [0] * M
for _ in range(N):
    like_list = list(map(int, input().split()))
    for like in like_list[1:]:
        loved_by_everyone[like] += 1

kinds = 0
for food in loved_by_everyone:
    kinds += 1 if food == N else 0
print(kinds)

N, M = map(int, input().split())
loved_by_everyone = [0] * M
for _ in range(N):
    like_list = list(map(int, input().split()))
    for like in like_list[1:]:
        loved_by_everyone[like - 1] += 1

kinds = 0
for food in loved_by_everyone:
    kinds += 1 if food == N else 0
print(kinds)


N, M = map(int, input().split())
favorites = {*tuple(range(1, M + 1))}
for _ in range(N):
    K, *fav = map(int, input().split())
    favorites = favorites & set(fav)
print(len(favorites))

N, M = map(int, input().split())
favorites = set(i for i in range(1, M + 1))
for _ in range(N):
    K, *fav = map(int, input().split())
    favorites = favorites & set(fav)
print(len(favorites))


from math import gcd

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

ans = A[0]

for i in range(1, N):
    ans = gcd(ans, A[i])

print(ans)

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

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

ans = A[0]

for i in range(1, N):
    ans = gcd(ans, A[i])

print(ans)


import sys

sys.setrecursionlimit(20000)

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

def gcd(a, b):
    la = max(a, b)
    sm = min(a, b)
    if la % sm == 0:
        return sm
    else:
        return gcd(sm, la - sm)

n = int(input())
A = inpl()

ans = gcd(A[0], A[1])
for a in A:
    ans = gcd(ans, a)
print(ans)

import sys

sys.setrecursionlimit(20000)

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

def gcd(a, b):
    la = max(a, b)
    sm = min(a, b)
    if la % sm == 0:
        return sm
    else:
        return gcd(sm, la - sm)

n = int(input())
A = inpl()
A.sort()
ans = gcd(A[0], A[1])
for a in A:
    ans = gcd(ans, a)
print(ans)


import fractions

N = int(input())
Ai = list(map(int, input().split()))
if Ai == [Ai[0]] * len(Ai):
    print(Ai[0])
    quit()

i = 1
min = 1000000000
for a in Ai:
    for a2 in Ai[i:]:
        a_gcd = fractions.gcd(a, a2)
        if min > a_gcd:
            min = a_gcd
            if min <= 2:
                print(min)
                quit()
    i += 1

print(min)

import fractions

N = int(input())
Ai = list(map(int, input().split()))
if Ai == [Ai[0]] * len(Ai):
    print(Ai[0])
    quit()

# Ai.sort()

i = 1
min = 1000000000
a = Ai[0]
for a2 in Ai[1:]:
    a_gcd = fractions.gcd(a, a2)
    if min > a_gcd:
        min = a_gcd
        if min <= 2:
            print(min)
            quit()

print(min)


from functools import reduce
from functools import gcd

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

print(reduce(gcd, A))

from functools import reduce
from fractions import gcd

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

print(reduce(gcd, A))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03127/Python/s208362126.py", line 2, in <module>
    from functools import gcd
ImportError: cannot import name 'gcd' from 'functools' (/usr/lib/python3.10/functools.py)


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

while True:
    if len(A) == 1:
        break
    max_i = A.index(max(A))
    min_i = A.index(min(A))
    life = A[max_i] % A[min_i]
    if life == 0:
        A.pop(max_i)
    else:
        A[max_i] = life

print(A[0])

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

while True:
    if len(A) == 1:
        break
    pop_i = []
    A.sort()
    for i in range(1, len(A)):
        life = A[i] % A[0]
        if life == 1:
            print(life)
            exit()
        else:
            A[i] = life
    A = [n for n in A if n > 0]

print(A[0])


import math

input()
a = sorted((map(int, input().split())))
ans = a[0]
for i in range(1, len(a)):
    ans = math.gcd(ans, a[i])
print(ans)

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

input()
a = sorted((map(int, input().split())))
ans = a[0]
for i in range(1, len(a)):
    ans = gcd(ans, a[i])
print(ans)


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

while len(a) >= 2:
    min_a = min(a)

    # 最小値が２つある場合に一回はskipする
    flag = False
    for i in range(len(a)):
        if a[i] == min_a and not flag:
            flag = True
            continue
        if flag or a[i] != min_a:
            a[i] = a[i] % min_a
    while True:
        if a.count(0) > 0:
            a.remove(0)
        else:
            break
print(a[0])

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

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

ans = a[0]
for i in range(1, len(a)):
    ans = gcd(ans, a[i])
print(ans)


from math import gcd

N = int(input())
A = sorted([int(n) for n in input().split()], reverse=True)

x = A[0]
for i in range(1, N):
    x = gcd(x, A[i])
print(x)

from fractions import gcd

N = int(input())
A = sorted([int(n) for n in input().split()], reverse=True)

x = A[0]
for i in range(1, N):
    x = gcd(x, A[i])
print(x)


n = int(input())

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

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

def saidai_koyakusu(n, ns):
    if len(ns) == 1:
        return ns[0]
    return gcd(n, saidai_koyakusu(ns[0], ns[1:]))

if len(zombies) == 1:
    print(zombies[0])
else:
    print(saidai_koyakusu(zombies[0], zombies[1:]))

n = int(input())

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

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

m = zombies[0]
for i in range(1, len(zombies)):
    m = gcd(m, zombies[i])

print(m)


""" AtCoder """

import math

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

ans = A[0]

for i in range(1, N):
    ans = math.gcd(ans, A[i])

print(ans)

""" AtCoder """

from fractions import gcd

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

ans = A[0]

for i in range(1, N):
    ans = gcd(ans, A[i])

print(ans)


import sys

readline = sys.stdin.buffer.readline

def sss(A, N):
    A.sort()
    if A[0] == 0:
        A.remove(0)
    for i in range(1, len(A)):
        A[i] = A[i] % A[0]
    if A[0] == sum(A):
        print(sum(A))
    else:
        return sss(A, N)

def main():
    N = int(readline())
    A = list(map(int, readline().split()))

    sss(A, N)

main()

import sys

readline = sys.stdin.buffer.readline

def sss(A, N):
    A.sort()
    while A[0] == 0:
        A.remove(0)
    for i in range(1, len(A)):
        A[i] = A[i] % A[0]
    if A[0] == sum(A):
        print(sum(A))
    else:
        return sss(A, N)

def main():
    N = int(readline())
    A = list(map(int, readline().split()))

    sss(A, N)

main()


n = int(input())
a = sorted(list(map(int, input().split())))
while True:
    a = sorted(list(set(a)))
    tmp = sorted(a[:20])
    for i in tmp:
        if i == a[0]:
            continue
        elif i % a[0] == 0:
            a.remove(i)
        else:
            a.append(i % a[0])
            a.remove(i)
    if len(a) == 1:
        break
print(a[0])

n = int(input())
a = sorted(list(map(int, input().split())))
while True:
    a = sorted(list(set(a)))
    tmp = sorted(a[:])
    for i in tmp:
        if i == a[0]:
            continue
        elif i % a[0] == 0:
            a.remove(i)
        else:
            a.append(i % a[0])
            if i % a[0] == 1:
                print(1)
                exit()
            a.remove(i)
    if len(a) == 1:
        break
print(a[0])


import math

N = int(input())
A = [int(i) for i in input().split()]
ans = A[N - 1]
for i in range(N - 1):
    ans = math.gcd(ans, A[i])
print(ans)

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

N = int(input())
A = [int(i) for i in input().split()]
ans = A[N - 1]
for i in range(N - 1):
    ans = gcd(ans, A[i])
print(ans)


from functools import gcd

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

a = A[0]
for i in range(1, n):
    a = gcd(a, A[i])

print(a)

from fractions import gcd

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

a = A[0]
for i in range(1, n):
    a = gcd(a, A[i])

print(a)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03127/Python/s946665504.py", line 1, in <module>
    from functools import gcd
ImportError: cannot import name 'gcd' from 'functools' (/usr/lib/python3.10/functools.py)


import math

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

ans = A[0]
for i in range(1, N):
    ans = math.gcd(ans, A[i])
print(ans)

import fractions

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

ans = A[0]
for i in range(1, N):
    ans = fractions.gcd(ans, A[i])
print(ans)


import math
from functools import reduce

N = int(input())
A = [int(i) for i in input().split()]
print(reduce(math.gcd, A))

from fractions import gcd
from functools import reduce

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


import math
from functools import reduce

input()
print(reduce(math.gcd, map(int, input().split())))

from fractions import gcd
from functools import reduce

input()
print(reduce(gcd, map(int, input().split())))


from math import gcd

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

ret = gcd(a[0], a[1])
for e in a[2:]:
    ret = gcd(ret, e)

print(ret)

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

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

    return x

ret = gcd(a[0], a[1])

for e in a[2:]:
    ret = gcd(ret, e)

print(ret)


import fraction
from functools import reduce

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

print(reduce(fraction.gcd, As))

import fractions
from functools import reduce

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

print(reduce(fractions.gcd, As))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03127/Python/s866739157.py", line 1, in <module>
    import fraction
ModuleNotFoundError: No module named 'fraction'


from fractions import gcd

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

print(gcd(a))

from fractions import gcd
from functools import reduce

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

print(reduce(gcd, a))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03127/Python/s745389063.py", line 1, in <module>
    from fractions import gcd
ImportError: cannot import name 'gcd' from 'fractions' (/usr/lib/python3.10/fractions.py)


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

if all([i % min(lst) == 0 for i in lst]):
    print(min(lst))
    exit()

gcm = 1
j = 2
lmt = int(min(lst) ** 0.5) + 1
while j <= lmt:
    if all([i % j == 0 for i in lst]):
        lst = [i / j for i in lst]
        gcm *= j
    else:
        j += 1

print(gcm)

from functools import reduce

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

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

print(reduce(gcd, lst))


# -*- coding: utf-8 -*-
N = map(int, input())
A = list(map(int, input().split()))

while len(A) >= 2:
    x = A.pop(A.index(max(A)))
    y = min(A)
    n = x % y
    if n == 0:
        pass
    else:
        A.append(n)

print(A[0])

# -*- coding: utf-8 -*-
N = map(int, input())
A = list(map(int, input().split()))

while len(A) >= 2:
    idx = A.index(min(A))
    x = A.pop(idx)
    B = list()
    for i in range(len(A)):
        if A[i] % x != 0:
            B.append(A[i] % x)
    B.append(x)
    A = B[:]

print(A[0])


import functools
import math

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

gcd = functools.reduce(math.gcd, a)
print(gcd)

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

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

if n == 1:
    print(x[0])
else:
    element = gcd(x[0], x[1])
    if n == 2:
        print(element)
    else:
        for i in range(2, n):
            element = gcd(element, x[i])
        print(element)


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

def bubble_sort(lst):
    for i in reversed(range(len(lst))):
        for j in range(i):
            if lst[j] > lst[j + 1]:
                lst[j], lst[j + 1] = lst[j + 1], lst[j]

bubble_sort(a)
zero_monster_indexes = []

while True:
    for monster_i in range(1, len(a)):
        if a[monster_i] == 0:
            zero_monster_indexes.append(monster_i)
        else:
            a[monster_i] %= a[0]

            if a[monster_i] == 0:
                zero_monster_indexes.append(monster_i)

    for zero_monster_index in reversed(zero_monster_indexes):
        a.pop(zero_monster_index)
    zero_monster_indexes.clear()

    bubble_sort(a)

    if len(a) == 1:
        break

print(a[0])

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

a = sorted(a)
zero_monster_indexes = []

while True:
    for monster_i in range(1, len(a)):
        if a[monster_i] == 0:
            zero_monster_indexes.append(monster_i)
        else:
            a[monster_i] %= a[0]

            if a[monster_i] == 0:
                zero_monster_indexes.append(monster_i)

    for zero_monster_index in reversed(zero_monster_indexes):
        a.pop(zero_monster_index)
    zero_monster_indexes.clear()

    a = sorted(a)
    if len(a) == 1:
        break

print(a[0])


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

MAX_N = int(1e4)
dp = [[-1 for i in range(10)] for i in range(MAX_N + 10)]
for j in range(1, 9 + 1):
    dp[0][j] = 0

mc = [2, 5, 5, 4, 5, 6, 3, 7, 6]

for i in range(N + 1):
    for j in range(1, 9 + 1):
        if j not in A:
            continue

        if i < mc[j - 1]:
            continue

        for k in range(1, j + 1):
            tmp = dp[i - mc[j - 1]][k]
            if tmp == -1:
                continue
            if tmp == 0:
                tmp = ""
            tmp = str(tmp)
            dp[i][j] = max(dp[i][j], int(tmp + str(j)), int(str(j) + tmp))

ans = 0
for j in range(1, 9 + 1):
    ans = max(ans, dp[N][j])
print(ans)

import math

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

MAX_N = int(1e4)
dp = [-1 for i in range(MAX_N + 20)]
dp[0] = 0

mc = [2, 5, 5, 4, 5, 6, 3, 7, 6]

for i in range(N + 1):
    for j in A:
        tmp = dp[i]
        if tmp == -1:
            continue
        if tmp == 0:
            dp[i + mc[j - 1]] = max(dp[i + mc[j - 1]], j)
        else:
            dp[i + mc[j - 1]] = max(dp[i + mc[j - 1]], tmp * 10 + j)

ans = dp[N]
print(ans)


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

dp = dict.fromkeys(range(n + 1))  # dp[n]: n本使うときの桁数
dp[0] = 0

num = {1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
anum = sorted(
    dict(filter(lambda e: e[0] in a, num.items())).items(), reverse=True
)  # 後の計算用にsortしておく

for i in range(n):
    dp[i + 1] = dp[i]
    for e in anum:
        if i + 1 - e[1] >= 0:
            dp[i + 1] = max(dp[i + 1], dp[i + 1 - e[1]] + 1)

ans = ""
while dp[n] > 1:
    for e in anum:  # anum は降順sortされているので, 大きい順に確認
        if n - e[1] >= 0:
            if dp[n - e[1]] == dp[n] - 1:
                ans += str(e[0])
                n -= e[1]
                break

# 末尾桁は n =0(ちょうど使い切るように決定)
ans += str(list(filter(lambda e: e[1] == n, anum))[0][0])

print(ans)

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

dp = dict.fromkeys(range(n + 1))  # dp[n]: n本使うときの桁数
dp[0] = 0

num = {1: 2, 2: 5, 3: 5, 4: 4, 5: 5, 6: 6, 7: 3, 8: 7, 9: 6}
anum = sorted(
    dict(filter(lambda e: e[0] in a, num.items())).items(), reverse=True
)  # 後の計算用にsortしておく

for i in range(n):
    dp[i + 1] = -float("inf")
    for e in anum:
        if i + 1 - e[1] >= 0:
            dp[i + 1] = max(dp[i + 1], dp[i + 1 - e[1]] + 1)

ans = ""
while dp[n] > 1:
    for e in anum:  # anum は降順sortされているので, 大きい順に確認
        if n - e[1] >= 0:
            if dp[n - e[1]] == dp[n] - 1:
                ans += str(e[0])
                n -= e[1]
                break

# 末尾桁は n =0(ちょうど使い切るように決定)
ans += str(list(filter(lambda e: e[1] == n, anum))[0][0])

print(ans)


num = int(input().split())
ans = num[0] / num[1]
print(ans)

num = list(map(int, input().split()))
ans = num[0] / num[1]
print(ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03135/Python/s676135149.py", line 1, in <module>
    num = int(input().split())
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list'


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

max_ = list_L.pop(list_L.index(max(list_L)))

if max_ > sum(list_L):
    print("Yes")
else:
    print("No")

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

max_ = list_L.pop(list_L.index(max(list_L)))

if max_ >= sum(list_L):
    print("No")
else:
    print("Yes")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03136/Python/s177830460.py", line 4, in <module>
    max_ = list_L.pop(list_L.index(max(list_L)))
AttributeError: 'map' object has no attribute 'pop'


N = input()
L = map(int, input().split())
x = sorted(L)
Lmax = max(L)
y = x[0:-1]
ysum = sum(y)
print("Yes" if Lmax < ysum else "No")

N = int(input())
L = list(map(int, input().split()))
x = sorted(L)
Lmax = max(L)
y = x[0:-1]
ysum = sum(y)
print("Yes" if Lmax < ysum else "No")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03136/Python/s642487988.py", line 4, in <module>
    Lmax = max(L)
ValueError: max() arg is an empty sequence


import sys

n, m = map(int, input().split())
x = list(map(int, input().split()))
if m == 1:
    print(0)
    sys.exit()
if n == 1:
    print(max(x) - min(x))
    sys.exit()
x.sort()
a = []
for i in range(m - 1):
    a.append(abs(x[i] - x[i + 1]))
ans = sum(a)
a.sort(reverse=True)
for i in range(n - 1):
    ans -= a[i]
print(max(0, ans))

import sys

n, m = map(int, input().split())
x = list(map(int, input().split()))
if m == 1:
    print(0)
    sys.exit()
if n == 1:
    print(max(x) - min(x))
    sys.exit()
if n >= m:
    print(0)
    sys.exit()
x.sort()
a = []
for i in range(m - 1):
    a.append(abs(x[i] - x[i + 1]))
ans = sum(a)
a.sort(reverse=True)
for i in range(n - 1):
    ans -= a[i]
print(max(0, ans))


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

if N == 1:
    ans = max(X) - min(X)
    print(ans)
    exit()

if M == 1:
    ans = 0
    print(ans)
    exit()

Xs = sorted(X)

diff = []
for i in range(M - 1):
    tmp = Xs[i + 1] - Xs[i]
    diff.append(tmp)

rest = N - 2
for _ in range(rest):
    if diff[0] > diff[len(diff) - 1]:
        diff.pop(0)
    else:
        diff.pop()

ans = 0

for _ in range(len(diff) - 1):
    if diff[0] > diff[len(diff) - 1]:
        ans += diff[len(diff) - 1]
        diff.pop()
    else:
        ans += diff[0]
        diff.pop(0)

print(ans)

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

if N == 1:
    ans = max(X) - min(X)
    print(ans)
    exit()

if (M == 1) or (N >= M):
    ans = 0
    print(ans)
    exit()

Xs = sorted(X)

diff = []
for i in range(M - 1):
    tmp = Xs[i + 1] - Xs[i]
    diff.append(tmp)

diffs = sorted(diff)
print(sum(diffs[: (M - 1) - (N - 1)]))


def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    X_sort = sorted(X)
    diff = []
    for i in range(M - 1):
        diff.append(X_sort[i + 1] - X_sort[i])
    diff_sort = sorted(diff)
    if M == 1:
        print("0")
        return
    for _ in range(N - 1):
        diff_sort.pop()
    ans = 0
    for d in diff_sort:
        ans += d
    print(ans)

if __name__ == "__main__":
    main()

def main():
    N, M = map(int, input().split())
    X = list(map(int, input().split()))
    if N >= M:
        print("0")
        return
    X_sort = sorted(X)
    diff = []
    for i in range(M - 1):
        diff.append(X_sort[i + 1] - X_sort[i])
    diff_sort = sorted(diff)
    if N != 1:
        for _ in range(N - 1):
            diff_sort.pop()
    ans = 0
    for d in diff_sort:
        ans += d
    print(ans)

if __name__ == "__main__":
    main()


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

X.sort()
if N >= M:
    ans = 0
else:
    x_diff = [X[i + 1] - X[i] for i in range(len(X) - 1)]
    for _ in range(N - 1):
        x_diff.remove(max(x_diff))
    ans = sum(x_diff)

print(ans)

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

X.sort()
if N >= M:
    ans = 0
else:
    x_diff = [
        xn - x for xn, x in zip(X[1:], X[:-1])
    ]  # [X[i + 1] - X[i] for i in range(len(X) - 1)]
    # for _ in range(N - 1):
    #     x_diff.remove(max(x_diff))
    x_diff.sort(reverse=True)
    ans = sum(x_diff[N - 1 :])

print(ans)


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

x.sort()
s = [0] * (M - 1)
for i in range(M - 1):
    s[i] = x[i + 1] - x[i]

s.sort(reverse=True)

res = sum(s)
if M == 1:
    print(0)
    quit()
else:
    for i in range(N - 1):
        res -= s[i]

print(res)

N, M = map(int, input().split())
x = list(map(int, input().split()))
if N >= M:
    print(0)
    quit()

x.sort()
s = [0] * (M - 1)
for i in range(M - 1):
    s[i] = x[i + 1] - x[i]

s.sort(reverse=True)

res = sum(s)
if M == 1:
    print(0)
    quit()
else:
    for i in range(N - 1):
        res -= s[i]

print(res)


def main():
    N, M = map(int, input().split())
    X = sorted(list(map(int, input().split())))

    if M == 1:
        print(0)
    elif N == 1:
        print(max(X) - min(X))
    else:
        dx = [abs(X[m] - X[m + 1]) for m in range(M - 1)]
        for _ in range(N - 1):
            dx.pop(dx.index(max(dx)))
        print(sum(dx))

main()

def main():
    N, M = map(int, input().split())
    X = sorted(list(map(int, input().split())))

    if M == 1:
        print(0)
    elif N == 1:
        print(max(X) - min(X))
    else:
        if N > M:
            N = M
        dx = sorted([abs(X[m] - X[m + 1]) for m in range(M - 1)])
        print(sum(dx[: M - N]))

main()


n = int(input())
a, b = [], []
for _ in range(n):
    x, y = map(int, input().split())
    a.append(x)
    b.append(y)

who = True
dishes = list(range(n))
takahashi = aoki = 0
while dishes:
    if who:
        dishes.sort(key=lambda dish: (b[dish], a[dish]))
        takahashi += a[dishes.pop()]
    else:
        dishes.sort(key=lambda dish: (a[dish], b[dish]))
        aoki += b[dishes.pop()]
    who = not who

print(takahashi - aoki)

n = int(input())
dishes = []
for _ in range(n):
    a, b = map(int, input().split())
    dishes.append((a, b, a + b))
dishes.sort(key=lambda dish: dish[2], reverse=True)

x = y = 0
for i in range(n):
    a, b, _ = dishes[i]
    if i % 2 == 0:
        x += a
    else:
        y += b

print(x - y)


# Different Strokes
n = int(input())
a, b = list(), list()
for _ in range(n):
    a_, b_ = map(int, input().split())
    a.append(a_)
    b.append(b_)
a_sort = sorted(a)
b_sort = sorted(b)
ans = 0
while True:
    const = b_sort.pop()
    indexes = list()
    for i in range(len(b)):
        if b[i] == const:
            indexes.append(i)
    m = 0
    ind = 0
    for i in indexes:
        if a[i] >= m:
            ind = i
            m = a[i]
    ans += m
    a_sort.remove(m)
    del a[ind]
    del b[ind]
    if not a:
        exit(print(ans))

    const = a_sort.pop()
    indexes = list()
    for i in range(len(a)):
        if a[i] == const:
            indexes.append(i)
    m = 0
    ind = 0
    for i in indexes:
        if b[i] >= m:
            ind = i
            m = b[i]
    ans -= m
    b_sort.remove(m)
    del a[ind]
    del b[ind]
    if not a:
        exit(print(ans))

# Different Strokes
n = int(input())
a, b = list(), list()
ab = list()
for i in range(n):
    a_, b_ = map(int, input().split())
    a.append(a_)
    b.append(b_)
    ab.append((a_, b_))
ans = 0
ab.sort(key=(lambda x: sum(x)), reverse=True)
for i, ab_ in enumerate(ab):
    if i % 2 == 0:
        ans += ab_[0]
    else:
        ans -= ab_[1]
print(ans)


def main():
    n = int(input())
    A = []
    B = []
    C = []
    for _ in range(n):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
        C.append(a + b)
    ans = 0
    isA = True
    while C:
        index = C.index(max(C))
        C.pop(index)
        if isA:
            ans += A[index]
        else:
            ans -= B[index]
        isA = not isA
    print(ans)

if __name__ == "__main__":
    main()

def main():
    n = int(input())
    A = []
    B = []
    C = {}
    for i in range(n):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
        C[str(i)] = a + b
    ans = 0
    isA = True
    for k, v in sorted(C.items(), key=lambda x: -x[1]):
        if isA:
            ans += A[int(k)]
        else:
            ans -= B[int(k)]
        isA = not isA
    print(ans)

if __name__ == "__main__":
    main()


def main():
    N = int(input())
    a = []
    b = []
    for _ in range(N):
        ai, bi = map(int, input().split())
        a.append(ai)
        b.append(bi)
    ans = 0
    s = 1
    while True:
        if sum(a) == 0:
            print(ans)
            exit()
        ma = a.pop()
        ans += ma * s
        b.pop()
        t = a
        a = b
        b = t
        s *= -1

main()

def main():
    N = int(input())
    ab = [[int(i) for i in input().split()] for _ in range(N)]
    ab = sorted(ab, key=lambda x: x[0] + x[1], reverse=True)
    ans = 0
    for i in range(N):
        if i % 2 == 0:
            ans += ab[i][0]
        else:
            ans -= ab[i][1]
    print(ans)

main()


#!/usr/bin/env python3
N, M = map(int, input().split())
g = [[] for _ in range(N)]
rg = [[] for _ in range(N)]
for _ in range(N - 1 + M):
    A, B = (int(x) - 1 for x in input().split())
    g[A].append(B)
    rg[B].append(A)

def dfs(s):
    global ts
    global used
    used[s] = True
    for t in g[s]:
        if not used[t]:
            dfs(t)
    ts.append(s)

def tsort():
    global ts
    for i in range(N):
        dfs(i)
    ts = ts[::-1]

used = [False] * N
ts = []
tsort()

mp = [None] * N
for i, x in enumerate(ts):
    mp[x] = i

ans = [0] * N
for t in ts[1:]:
    if rg[t]:
        ans[t] = ts[max(mp[s] for s in rg[t])] + 1

for x in ans:
    print(x)

#!/usr/bin/env python3
import sys

sys.setrecursionlimit(100000)
N, M = map(int, input().split())
g = [[] for _ in range(N)]
rg = [[] for _ in range(N)]
for _ in range(N - 1 + M):
    A, B = (int(x) - 1 for x in input().split())
    g[A].append(B)
    rg[B].append(A)

def dfs(s):
    global ts
    global used
    used[s] = True
    for t in g[s]:
        if not used[t]:
            dfs(t)
    ts.append(s)

def tsort():
    global ts
    for i in range(N):
        dfs(i)
    ts = ts[::-1]

used = [False] * N
ts = []
tsort()

mp = [None] * N
for i, x in enumerate(ts):
    mp[x] = i

ans = [0] * N
for t in ts[1:]:
    if rg[t]:
        ans[t] = ts[max(mp[s] for s in rg[t])] + 1

for x in ans:
    print(x)


n, m = map(int, input().split())
g = [[] for _ in range(n)]
inv = [0] * n
for _ in range(n - 1 + m):
    a, b = map(int, input().split())
    g[a - 1].append(b - 1)
    inv[b - 1] += 1
for i in range(n):
    if inv[i] == 0:
        root = i
        break
d = [0] * n
s = [root]
while s:
    p = s.pop()
    for node in g[p]:
        d[node] = max(d[node], d[p] + 1)
        s.append(node)
ans = [0] * n
for i in range(n):
    for node in g[i]:
        if d[node] == d[i] + 1:
            ans[node] = i + 1
for x in ans:
    print(x)

n, m = map(int, input().split())
g = [[] for _ in range(n)]
inv = [0] * n
for _ in range(n - 1 + m):
    a, b = map(int, input().split())
    g[a - 1].append(b - 1)
    inv[b - 1] += 1
for i in range(n):
    if inv[i] == 0:
        root = i
        break
d = [0] * n
s = [root]
while s:
    p = s.pop()
    for node in g[p]:
        inv[node] -= 1
        if inv[node] == 0:
            d[node] = max(d[node], d[p] + 1)
            s.append(node)
ans = [0] * n
for i in range(n):
    for node in g[i]:
        if d[node] == d[i] + 1:
            ans[node] = i + 1
for x in ans:
    print(x)


h, w, _ = [int(i) for i in input()]
ans = h * w // 2
print(ans)

h, w, _ = [int(i) for i in input().split()]
ans = h * w // 2
print(ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s129162499.py", line 1, in <module>
    h, w, _ = [int(i) for i in input()]
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s129162499.py", line 1, in <listcomp>
    h, w, _ = [int(i) for i in input()]
ValueError: invalid literal for int() with base 10: ' '


def main() -> None:
    ab, bc, ca = map(int, input())
    print(ab * bc // 2)

if __name__ == "__main__":
    main()

def main() -> None:
    ab, bc, ca = map(int, input().split())
    print(ab * bc // 2)

if __name__ == "__main__":
    main()

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s388138041.py", line 7, in <module>
    main()
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s388138041.py", line 2, in main
    ab, bc, ca = map(int, input())
ValueError: invalid literal for int() with base 10: ' '


LL = list(map(int, input().split())).sort()
R = LL[0] * LL[1] // 2
print(R)

LL = list(map(int, input().split()))
LL.sort()
R = LL[0] * LL[1] // 2
print(R)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s826877996.py", line 2, in <module>
    R = LL[0] * LL[1] // 2
TypeError: 'NoneType' object is not subscriptable


s = int(input())
an = []
an.append(s)
n = s
while an.count(4) != 2:
    if n % 2 == 0:
        n /= 2
        an.append(int(n))
    else:
        n = 3 * n + 1
        an.append(int(n))
if an.index(1 or 2) == 0:
    print(4)
else:
    print(an.index(4) + 4)

x, y, z = map(int, input().split())
print(int(x * y / 2))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s174683495.py", line 1, in <module>
    s = int(input())
ValueError: invalid literal for int() with base 10: '3 4 5'


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

print(a * b / 2)

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

print(int(a * b / 2))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s543024524.py", line 1, in <module>
    a, b, c = map(int, input())
ValueError: invalid literal for int() with base 10: ' '


from typing import List

def main() -> None:
    ab, bc, _ = get_params()
    print(area(ab, bc))

def get_params() -> List[int]:
    return [int(s) for s in input().split()]

def area(ab: int, bc: int) -> int:
    return ab * bc // 2

if __name__ == "__main__":
    main()

def main():
    ab, bc, _ = get_params()
    print(area(ab, bc))

def get_params():
    return [int(s) for s in input().split()]

def area(ab, bc):
    return ab * bc // 2

if __name__ == "__main__":
    main()


AB, BC, CA = int(input())

print((AB * BC) // 2)

AB, BC, CA = map(int, input().split())

print((AB * BC) // 2)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03145/Python/s114139853.py", line 1, in <module>
    AB, BC, CA = int(input())
ValueError: invalid literal for int() with base 10: '3 4 5'


s = int(input())
an = []
an.append(s)
n = s
if an.index(1 or 2) == 0:
    print(4)
while an.count(4) != 2:
    if n % 2 == 0:
        n /= 2
        an.append(int(n))
    else:
        n = 3 * n + 1
        an.append(int(n))
print(an.index(4) + 4)

s = int(input())
an = []
an.append(s)
n = s
while an.count(4) != 2:
    if n % 2 == 0:
        n /= 2
        an.append(int(n))
    else:
        n = 3 * n + 1
        an.append(int(n))
if an.index(1) == 0:
    print(4)
elif an.index(2) == 0:
    print(4)
else:
    print(an.index(4) + 4)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03146/Python/s842061170.py", line 5, in <module>
    if an.index(1 or 2) == 0:
ValueError: 1 is not in list


s = int(input())
a = [s]
z = set(s)
idx = 1
for i in range(10**8):
    idx += 1
    if a[i] % 2 == 0:
        ai = a[i] // 2
    else:
        ai = 3 * a[i] + 1
    if ai in z:
        print(idx)
        exit()
    a.append(ai)
    z.add(ai)

s = int(input())
a = [s]
z = set([s])
idx = 1
for i in range(10**8):
    idx += 1
    if a[i] % 2 == 0:
        ai = a[i] // 2
    else:
        ai = 3 * a[i] + 1
    if ai in z:
        print(idx)
        exit()
    a.append(ai)
    z.add(ai)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03146/Python/s047431119.py", line 3, in <module>
    z = set(s)
TypeError: 'int' object is not iterable


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

while max(H) > 0:
    grp = [[]]
    for i, h in enumerate(H):
        if h == 0:
            if len(grp[-1]) > 0:
                grp.append([])
        else:
            grp[-1].append((i, h))
    for g in grp:
        mi = min([h for _, h in g])
        ans += mi
        for i, _ in g:
            H[i] -= mi

print(ans)

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

while max(H) > 0:
    grp = [[]]
    for i, h in enumerate(H):
        if h == 0:
            if len(grp[-1]) > 0:
                grp.append([])
        else:
            grp[-1].append((i, h))
    for g in grp:
        if len(g) == 0:
            continue
        mi = min([h for _, h in g])
        ans += mi
        for i, _ in g:
            H[i] -= mi

print(ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03147/Python/s431171639.py", line 14, in <module>
    mi = min([h for _, h in g])
ValueError: min() arg is an empty sequence


import sys

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

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

    dflag = 0
    cmin = 0
    cmax = h[0]
    count = 0
    for i in range(1, N):
        if h[i - 1] < h[i] and dflag == 1:
            count += cmax - cmin
            cmax = h[i]
            dflag = 0
            cmin = h[i - 1]

        elif h[i - 1] > h[i]:
            dflag = 1

        elif h[i - 1] < h[i]:
            cmax = h[i]

    if dflag == 1:
        count += cmax - cmin
    else:
        count += max(cmax, h[i]) - cmin

    print(count)

if __name__ == "__main__":
    main()

import sys

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

def main():
    N = int(input())
    if N == 1:
        print(input())
        exit()
    h = list(map(int, input().split()))

    dflag = 0
    cmin = 0
    cmax = h[0]
    count = 0
    for i in range(1, N):
        if h[i - 1] < h[i] and dflag == 1:
            count += cmax - cmin
            cmax = h[i]
            dflag = 0
            cmin = h[i - 1]

        elif h[i - 1] > h[i]:
            dflag = 1

        elif h[i - 1] < h[i]:
            cmax = h[i]

    if dflag == 1:
        count += cmax - cmin
    else:
        count += max(cmax, h[i]) - cmin

    print(count)

if __name__ == "__main__":
    main()


import operator
import collections

n, k = map(int, input().split())
sushies = []
for _ in range(n):
    t, d = map(int, input().split())
    sushies.append((t, d))

sushies.sort(key=operator.itemgetter(1), reverse=True)

dishes = sushies[:k]
c = collections.Counter(t for t, d in dishes)
a = sum(d for t, d in dishes)
answer = a + len(c) ** 2

for t, d in sushies[k:]:
    if t in c:
        continue

    x = -1
    for i in reversed(range(k)):
        if c[dishes[i][0]] > 1:
            x = i
            break

    if x == -1:
        break

    a = a + d - dishes[x][1]
    c[t] += 1
    c[dishes[x][0]] -= 1
    del dishes[x]
    dishes.append((t, d))

    answer = max(answer, a + len(c) ** 2)

print(answer)

import operator
import collections

n, k = map(int, input().split())
sushies = []
for _ in range(n):
    t, d = map(int, input().split())
    sushies.append((t, d))

sushies.sort(key=operator.itemgetter(1), reverse=True)

dishes = sushies[:k]
c = collections.Counter(t for t, d in dishes)
a = sum(d for t, d in dishes)
answer = a + len(c) ** 2
x = k - 1
for t, d in sushies[k:]:
    if t in c:
        continue

    while x >= 0:
        if c[dishes[x][0]] > 1:
            break
        x -= 1

    if x == -1:
        break

    a = a + d - dishes[x][1]
    c[t] += 1
    c[dishes[x][0]] -= 1
    del dishes[x]
    dishes.append((t, d))

    answer = max(answer, a + len(c) ** 2)

print(answer)


import heapq

n, k = map(int, input().split())
sushi = [list(map(int, input().split())) for _ in range(n)]
sushi.sort(key=lambda x: x[1])
t = {}
x = []
z = 0
for i in range(n - 1, n - k - 1, -1):
    ti, di = sushi[i]
    if ti in t.keys():
        heapq.heappush(x, di)
        t[ti] += 1
    else:
        t[ti] = 1
    z += di

ans = z + len(t.keys()) ** 2
for i in range(n - k - 1, -1, -1):
    ti, di = sushi[i]
    if ti not in t.keys():
        t[ti] = 1
        z += di - heapq.heappop(x)
        ans = max(ans, z + len(t.keys()) ** 2)
        k += 1

print(ans)

import heapq

n, k = map(int, input().split())
sushi = [list(map(int, input().split())) for _ in range(n)]
sushi.sort(key=lambda x: x[1])
t = {}
x = []
z = 0
for i in range(n - 1, n - k - 1, -1):
    ti, di = sushi[i]
    if ti in t.keys():
        heapq.heappush(x, di)
        t[ti] += 1
    else:
        t[ti] = 1
    z += di

p = len(t.keys())
ans = z + p**2
for i in range(n - k - 1, -1, -1):
    if len(x) == 0:
        break
    ti, di = sushi[i]
    if ti not in t.keys():
        t[ti] = 1
        z += di - heapq.heappop(x)
        p += 1
        ans = max(ans, z + p**2)

print(ans)


from itertools import permutations

N, K = map(int, input().split())
inputs = [[int(i) for i in input().split()] for _ in range(N)]

ans = 0
for items in permutations(inputs, K):
    tmp = 0
    sets = set()
    for i in range(K):
        tmp += items[i][1]
        sets.add(items[i][0])
    tmp += len(sets) * len(sets)
    ans = max(ans, tmp)

print(ans)

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

inputs = []
priority_queue = []
queue = []
sets = set()

for _ in range(N):
    key, value = map(int, input().split())
    inputs.append((value, key))

inputs.sort(reverse=True)  # valueで降順のソートをかけてる

for i in range(K):
    value, key = inputs[i]
    if key in sets:
        queue.append(value)
    else:
        priority_queue.append(value)
        sets.add(key)

sum_priority_queue = sum(priority_queue)
sum_queue = sum(queue)
kinds = len(sets)
ans = sum_priority_queue + sum_queue + kinds**2
for i in range(K, N):
    if not queue:
        break
    value, key = inputs[i]
    if key in sets:
        continue
    sets.add(key)
    sum_queue -= queue.pop()
    sum_priority_queue += value
    kinds += 1
    ans = max(ans, sum_priority_queue + sum_queue + kinds**2)

print(ans)


from collections import defaultdict
from heapq import heappush, heappop

n, k = map(int, input().split())
dic = defaultdict(list)
for _ in range(n):
    t, d = map(int, input().split())
    dic[t].append(d)

maxs = []
for key in dic:
    dic[key].sort()
    maxs.append((dic[key].pop(), key))

maxs.sort(reverse=True)
queSize = 0
que = []
queScore = 0
defaultScore = 0
cnt = 0
ans = 0
for v, key in maxs:
    defaultScore += v + cnt * 2 + 1
    cnt += 1
    for add in dic[key]:
        heappush(que, add)
        queSize += 1
        queScore += add
    while queSize > k - cnt:
        queScore -= heappop(que)
        queSize -= 1
    ans = max(ans, defaultScore + queScore)

print(ans)

from collections import defaultdict
from heapq import heappush, heappop

n, k = map(int, input().split())
dic = defaultdict(list)
for _ in range(n):
    t, d = map(int, input().split())
    dic[t].append(d)

maxs = []
for key in dic:
    dic[key].sort()
    maxs.append((dic[key].pop(), key))

maxs.sort(reverse=True)
queSize = 0
que = []
queScore = 0
defaultScore = 0
cnt = 0
ans = 0
for v, key in maxs:
    defaultScore += v + cnt * 2 + 1
    cnt += 1
    if cnt >= k:
        ans = max(ans, defaultScore)
        break
    for add in dic[key]:
        heappush(que, add)
        queSize += 1
        queScore += add
    while queSize > k - cnt:
        queScore -= heappop(que)
        queSize -= 1
    ans = max(ans, defaultScore + queScore)

print(ans)


s = input()
key = "keyence"
ptr = 0

for c in s:
    if c == key[ptr]:
        ptr += 1

print("YES" if ptr == 7 else "NO")

s = list(input())
ls = len(s)
key = "keyence"
if "".join(s) == key:
    print("YES")
    exit()
f = False
for l in range(ls):
    for r in range(l + 1, ls):
        f |= "".join(["".join(s[:l]), "".join(s[r:])]) == key

print("YES" if f else "NO")


S = input()

target = "keyence"
now = 0
start = None
end = None
for i in range(len(S)):
    if target[now] == S[i]:
        now += 1
        if start is not None and end is None:
            end = i
    elif start is not None:
        continue
    else:
        start = i

if start is None:
    pred = S
elif end is None:
    pred = S[:start]
else:
    pred = S[:start] + S[end:]

if pred == target:
    print("YES")
else:
    print("NO")

S = input()

target = "keyence"
N = len(target)

for i in range(8):
    s = S[:i] + S[len(S) - N + i :]
    if s == target:
        print("YES")
        break
else:
    print("NO")


S = str(input())
s = input()
for i in range(len(s)):
    for j in range(i, len(s)):
        a = s[:i] + s[j:]
        if a == "keyence":
            print("YES")
            exit()
print("NO")

s = str(input())
for i in range(len(s)):
    for j in range(i, len(s)):
        a = s[:i] + s[j:]
        if a == "keyence":
            print("YES")
            exit()
print("NO")

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03150/Python/s743625929.py", line 2, in <module>
    s = input()
EOFError: EOF when reading a line


# 2019/01/13
# KEYENCE Programming Contest 2019 - B

# Input
s = input()

# Init
key_str = "keyence"
search_idx = 0
okflg = 0
ngcnt = 0

# Search
for idx in range(len(s)):
    if s[idx] == key_str[search_idx]:
        search_idx += 1
        okflg = 1
    else:
        if okflg == 1:
            ngcnt += 1
            okflg = 0
        if ngcnt > 1:
            break

# Check
if search_idx == len(key_str):
    ans = "YES"
else:
    ans = "NO"

# Output
print(ans)

# 2019/01/13
# KEYENCE Programming Contest 2019 - B

# Input
s = input()

# Init
key_str = "keyence"
ans = "NO"
search_idx = 0

# Search
if s[0] == key_str[0]:
    # Pattern 2 or 3
    for idx in range(len(s)):
        if s[idx] == key_str[search_idx]:
            search_idx += 1
            if search_idx == len(key_str):
                # Pattern 3
                ans = "YES"
                break

        else:
            # Pattern 2
            for idx2 in range(len(s) - len(key_str) + search_idx, len(s)):
                if s[idx2] == key_str[search_idx]:
                    search_idx += 1
                    if search_idx == len(key_str):
                        ans = "YES"
            break
else:
    # Pattern 1
    for idx in range(len(s) - len(key_str), len(s)):
        if s[idx] == key_str[search_idx]:
            search_idx += 1
            if search_idx == len(key_str):
                ans = "YES"
                break

# Output
print(ans)


s = input()
w = list("keyence")

st = ""
i_w = 0
delete = []

for i in s:
    if i == w[i_w]:
        i_w += 1
        if not st == "":
            delete.append(st)
            st = ""
    else:
        st += i
else:
    if not st == "":
        delete.append(st)

if i_w == 7 and len(delete) <= 1:
    ans = "YES"
else:
    ans = "NO"
print(ans)

s = input()

w = "keyence"
ans = "NO"

# keyencexxxxx
if s[:7] == w:
    ans = "YES"

# xxxxkeyence
if s[-7:] == w:
    ans = "YES"

# key xxx ence
for i in range(1, 7):
    ss = w[:i]
    tt = w[-7 + i :]
    if s[: len(ss)] == ss and s[-len(tt) :] == tt:
        ans = "YES"
        break

print(ans)


n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
L_over = []
L_short = []
for i in range(n):
    c = A[i] - B[i]
    if c > 0:
        L_over.append(c)
    elif c < 0:
        L_short.append(-c)
L_over.sort(reverse=True)
if sum(L_over) < sum(L_short):
    print(-1)
else:
    cnt = len(L_short)
    p = 0
    for i in range(len(L_over)):
        if p >= sum(L_short):
            break
        p += L_over[i]
        cnt += 1
    print(cnt)

n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
over = []
short = 0
cnt = 0
for i in range(n):
    c = A[i] - B[i]
    if c > 0:
        over.append(c)
    elif c < 0:
        short -= c
        cnt += 1
if sum(over) < short:
    print(-1)
else:
    over.sort(reverse=True)
    s = 0
    i = 0
    while s < short:
        s += over[i]
        i += 1
    cnt += i
    print(cnt)


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

print((N - W + 1) * (N - H + 1))

N = int(input())
W = int(input())
H = int(input())

print((N - W + 1) * (N - H + 1))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03155/Python/s974033507.py", line 1, in <module>
    N, W, H = map(int, input().split())
ValueError: not enough values to unpack (expected 3, got 1)


def dfs(i, j, c):
    visited[i][j] = 1
    current.append((i, j))
    for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
        ni, nj = i + di, j + dj
        if not (0 <= ni < H and 0 <= nj < W and not visited[ni][nj]):
            continue
        if S[ni][nj] == c:
            continue
        dfs(ni, nj, not c)

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

ans = 0
visited = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] and not visited[i][j]:
            current = []
            dfs(i, j, True)
            b, w = 0, 0
            for k, l in current:
                if S[k][l]:
                    b += 1
                else:
                    w += 1
            ans += b * w
print(ans)

from sys import setrecursionlimit

def dfs(i, j, c):
    visited[i][j] = 1
    current.append((i, j))
    for di, dj in (1, 0), (-1, 0), (0, 1), (0, -1):
        ni, nj = i + di, j + dj
        if not (0 <= ni < H and 0 <= nj < W and not visited[ni][nj]):
            continue
        if S[ni][nj] == c:
            continue
        dfs(ni, nj, not c)

setrecursionlimit(2 * 10**5)
H, W = map(int, input().split())
S = [[c == "#" for c in input()] for _ in range(H)]

ans = 0
visited = [[0] * W for _ in range(H)]
for i in range(H):
    for j in range(W):
        if S[i][j] and not visited[i][j]:
            current = []
            dfs(i, j, True)
            b, w = 0, 0
            for k, l in current:
                if S[k][l]:
                    b += 1
                else:
                    w += 1
            ans += b * w
print(ans)


import sys

def input():
    return sys.stdin.readline()[:-1]

def ii(t: type = int):
    return t(input())

def il(t: type = int):
    return list(map(t, input().split()))

def imi(N: int, t: type = int):
    return [ii(t) for _ in range(N)]

def iml(N: int, t: type = int):
    return [il(t) for _ in range(N)]

H, W = il()
S = imi(H, str)
sharp_pos = []
for i in range(H):
    for j in range(W):
        if S[i][j] == "#":
            sharp_pos.append((i, j))
c = 0
k = 0
pre_cx, pre_cy = 0, 0

board = S[:]
C = 0

def saiki(pos_list, ignore=None):
    global C
    for cx, cy in pos_list:
        p_list = []
        if ignore is None:
            ignore = []
        wanna_char = "." if board[cx][cy] == "#" else "#"
        for d in ((-1, 0), (0, -1), (1, 0), (0, 1)):
            tx = cx + d[1]
            ty = cy + d[0]
            if (
                tx >= 0
                and ty >= 0
                and tx < H
                and ty < W
                and (tx, ty) not in ignore
                and board[tx][ty] == wanna_char
            ):
                ignore.append((cx, cy))
                p_list.append((tx, ty))
                C += 1
        saiki(p_list, ignore)

saiki(sharp_pos)
print(C)

import sys
from itertools import product

sys.setrecursionlimit(200000)

def input():
    return sys.stdin.readline()[:-1]

def ii(t: type = int):
    return t(input())

def il(t: type = int):
    return list(map(t, input().split()))

def imi(N: int, t: type = int):
    return [ii(t) for _ in range(N)]

def iml(N: int, t: type = int):
    return [il(t) for _ in range(N)]

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

H, W = il()
S = imi(H, str)
tree = UnionFind(H * W)
for i, j in product(range(H), range(W)):
    for d in ((-1, 0), (0, -1), (1, 0), (0, 1)):
        x = i + d[0]
        y = j + d[1]
        if 0 <= x < H and 0 <= y < W:
            if S[i][j] != S[x][y]:
                tree.union((i * W + j), (x * W + y))

dot = [0] * (H * W)
sharp = [0] * (H * W)
for i, j in product(range(H), range(W)):
    if S[i][j] == ".":
        dot[tree.find(i * W + j)] += 1
    else:
        sharp[tree.find(i * W + j)] += 1

ans = 0
for i in range(H * W):
    ans += dot[i] * sharp[i]
print(ans)


import sys

sys.setrecursionlimit(10**6)

def dfs(x, y, matrix, visited, isWhite):
    global black, white
    dxy = [[1, 0], [-1, 0], [0, -1], [0, 1]]
    visited[y][x] = True
    w = len(matrix[0])
    h = len(matrix)

    for dx, dy in dxy:
        nx = x + dx
        ny = y + dy

        if nx < 0 or w <= nx or ny < 0 or h <= ny:
            continue

        if visited[ny][nx] is True:
            continue

        if (matrix[ny][nx] == "#" and isWhite is False) or (
            matrix[ny][nx] == "." and isWhite is True
        ):
            continue

        if matrix[ny][nx] == "#":
            black += 1
        else:
            white += 1

        isWhite = not isWhite
        dfs(nx, ny, matrix, visited, isWhite)
        isWhite = not isWhite

    return

h, w = map(int, input().split())
matrix = [""] * h
for i in range(h):
    matrix[i] = input()

ans = 0
visited = [[False] * w for _ in range(h)]

for i in range(h):
    for j in range(w):
        if matrix[i][j] == "#" and visited[i][j] is False:
            black = 1
            white = 0
            dfs(j, i, matrix, visited, False)
            ans += black * white

print(ans)


# -*- coding: utf-8 -*-
# Input#
n = int(input())
# n, k = map(int, input().split())
h = list(map(int, input().split()))

h = [-1] + h

ans = 0

memo = [-1] * (n + 1)
memo[1] = 0
memo[2] = abs(h[2] - h[1])

def dp(i):
    if memo[i] != -1:
        return memo[i]
    else:
        hop1 = dp(i - 1) + abs(h[i] - h[i - 1])
        hop2 = dp(i - 2) + abs(h[i] - h[i - 2])
        memo[i] = min(hop1, hop2)
        return memo[i]

for i in range(n):
    tmp = dp(i)

ans = dp(n)

print("{}".format(ans))

# -*- coding: utf-8 -*-
# Input#
n = int(input())
# n, k = map(int, input().split())
h = list(map(int, input().split()))

h = [-1] + h

ans = 0

memo = [-1] * (n + 1)
memo[1] = 0
memo[2] = abs(h[2] - h[1])

def dp(i):
    if memo[i] != -1:
        return memo[i]
    else:
        hop1 = dp(i - 1) + abs(h[i] - h[i - 1])
        hop2 = dp(i - 2) + abs(h[i] - h[i - 2])
        memo[i] = min(hop1, hop2)
        return memo[i]

for i in range(n):
    if i == 0 or i == 1 or i == 2:
        continue
    hop1 = memo[i - 1] + abs(h[i] - h[i - 1])
    hop2 = memo[i - 2] + abs(h[i] - h[i - 2])
    memo[i] = min(hop1, hop2)

ans = dp(n)

print("{}".format(ans))


"""
author : halo2halo
date : 4, Feb, 2020
"""

import sys

# import itertools
# import math

# import numpy as np

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

N, *H = map(int, readline().split())
dp = [0] * N
dp[1] = abs(H[1] - H[0])

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

ans = dp[-1]
print(ans)

"""
author : halo2halo
date : 4, Feb, 2020
"""

import sys

# import itertools
# import math

# import numpy as np

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

N, *H = map(int, read().split())
dp = [0] * N
dp[1] = abs(H[1] - H[0])

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

ans = dp[-1]
print(ans)

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s149948517.py", line 19, in <module>
    dp[1] = abs(H[1] - H[0])
IndexError: list index out of range


import sys

# import numpy as np

def main():
    f = sys.stdin.buffer
    N, K = map(int, f.readline().split())
    H = list(map(int, f.readline().split()))
    dp = [0] * N
    for i in range(1, N):
        dp[i] = min(
            dp[i - k - 1] + abs(H[i] - H[i - k - 1]) for k in range(K) if i - k - 1 >= 0
        )
    print(dp[-1])

if __name__ == "__main__":
    main()

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

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s516514400.py", line 19, in <module>
    main()
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s516514400.py", line 8, in main
    N, K = map(int, f.readline().split())
ValueError: not enough values to unpack (expected 2, got 1)


import sys
import threading

sys.setrecursionlimit(200000000)
threading.stack_size(134217728)

class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res

def solve(problem: SearchProblem):
    memo = {}

    def future_cost(s):
        if s in memo:
            return memo[s]

        if problem.isEnd(s):
            memo[s] = 0
            return 0
        else:
            memo[s] = min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )
            return memo[s]

    return future_cost(1)

def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))

if __name__ == "__main__":
    main_thread = threading.Thread(target=main)
    main_thread.start()
    main_thread.join()

def solve(n):
    table = [0 for i in range(N + 1)]
    for i in range(1, n + 1):
        if i == 1:
            table[1] = 0
        elif i == 2:
            table[2] = abs(H[2] - H[1])
        else:
            table[i] = min(
                table[i - 1] + abs(H[i] - H[i - 1]), table[i - 2] + abs(H[i] - H[i - 2])
            )
    return table[n]

if __name__ == "__main__":
    N = int(input())
    H = [0] + [int(x) for x in input().split(" ")]

    print(solve(N))

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s452152081.py", line 53, in <module>
    main_thread.start()
  File "/usr/lib/python3.10/threading.py", line 935, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread


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

# dp[i][j]: 足場iまで見た時 jまでの最小コスト
dp = [[0 for j in range(n)] for i in range(n)]

dp[1][1] = abs(h[1] - h[0])

for i in range(n):
    if i == 0 or i == 1:
        continue

    dp[i] = dp[i - 1]

    cost1jump = dp[i - 1][i - 1] + abs(h[i] - h[i - 1])
    cost2jump = dp[i - 1][i - 2] + abs(h[i] - h[i - 2])
    dp[i][i] = min(cost1jump, cost2jump)

print(dp[-1][-1])

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

# dp[i][j]: 足場iまで見た時 jまでの最小コスト
dp = [0 for i in range(n)]

dp[1] = abs(h[1] - h[0])

for i in range(n):
    if i == 0 or i == 1:
        continue

    cost1jump = dp[i - 1] + abs(h[i] - h[i - 1])
    cost2jump = dp[i - 2] + abs(h[i] - h[i - 2])
    dp[i] = min(cost1jump, cost2jump)

print(dp[-1])


import math

N = int(input())
heights = list(map(int, input().strip().split()))

dp = [math.inf for _ in range(N)]

dp[0] = 0
if len > 1:
    dp[1] = abs(heights[1] - heights[0])

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

print(dp[N - 1])

N = int(input())
heights = list(map(int, input().strip().split()))

dp = [float("inf") for _ in range(N)]

dp[0] = 0
if N > 1:
    dp[1] = abs(heights[1] - heights[0])

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

print(dp[N - 1])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s290255807.py", line 9, in <module>
    if len > 1:
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int'


def sub():
    N = int(input())
    hs = [int(e) for e in input().split()]

    def optimal_value(a_index):
        if a_index >= N - 1:
            return 0

        if a_index < N - 2:
            a = optimal_value(a_index + 1) + abs(hs[a_index + 1] - hs[a_index])
            b = optimal_value(a_index + 2) + abs(hs[a_index + 2] - hs[a_index])
            return min(a, b)
        else:
            return optimal_value(a_index + 1) + abs(hs[a_index + 1] - hs[a_index])

    print(optimal_value(0))

sub()

def sub():
    N = int(input())
    hs = [int(e) for e in input().split()]
    optimal_values = [None for _ in range(N)]
    optimal_values[0] = 0
    for i in range(1, N):
        if i > 1:
            a = optimal_values[i - 1] + abs(hs[i] - hs[i - 1])
            b = optimal_values[i - 2] + abs(hs[i] - hs[i - 2])
            optimal_values[i] = min(a, b)
        else:
            optimal_values[i] = optimal_values[i - 1] + abs(hs[i] - hs[i - 1])
    print(optimal_values[-1])

sub()


import sys

sys.setrecursionlimit(500000)
N = int(input())
h = [int(i) for i in input().split()]

memo = [float("inf")] * N
memo[0], memo[1] = 0, abs(h[1] - h[0])

def frog(ith):
    if memo[ith] != float("inf"):
        return memo[ith]
    memo[ith] = min(
        frog(ith - 1) + abs(h[ith] - h[ith - 1]),
        frog(ith - 2) + abs(h[ith] - h[ith - 2]),
    )
    return memo[ith]

print(frog(N - 1))


import functools
import threading
import sys

class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res

def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)

def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))

if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024)
    threading.stack_size(128 * 1024 * 1024)
    threading.Thread(target=main).start()

import functools
import threading
import sys

class SearchProblem(object):
    def __init__(self, N, H):
        self.N = N
        self.H = H

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        res = []
        if i + 1 <= self.N:
            res.append((i + 1, abs(self.H[i + 1] - self.H[i])))
        if i + 2 <= self.N:
            res.append((i + 2, abs(self.H[i + 2] - self.H[i])))
        return res

def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)

def main():
    N = int(input())
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H)
    print(solve(problem))

if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03160/Python/s280441279.py", line 47, in <module>
    threading.Thread(target=main).start()
  File "/usr/lib/python3.10/threading.py", line 935, in start
    _start_new_thread(self._bootstrap, ())
RuntimeError: can't start new thread


n = int(input())
initial_vals = list(map(int, input().split(" ")))

table = [[None for x in range(n)] for x in range(n)]

def calc(from_stone, to_stone):
    if table[from_stone][to_stone] is not None:
        return table[from_stone][to_stone]
    elif (to_stone - from_stone) == 1:
        table[from_stone][to_stone] = abs(
            initial_vals[from_stone] - initial_vals[to_stone]
        )
        return table[from_stone][to_stone]
    elif (to_stone - from_stone) == 2:
        table[from_stone][to_stone] = min(
            abs(initial_vals[from_stone] - initial_vals[to_stone - 1])
            + abs(initial_vals[to_stone - 1] - initial_vals[to_stone]),
            abs(initial_vals[from_stone] - initial_vals[to_stone]),
        )
        return table[from_stone][to_stone]
    else:
        table[from_stone][to_stone] = min(
            calc(from_stone, to_stone - 1) + calc(to_stone - 1, to_stone),
            calc(from_stone, to_stone - 2) + calc(to_stone - 2, to_stone),
        )
        return table[from_stone][to_stone]

print(calc(0, n - 1))

n = int(input())
initial_vals = list(map(int, input().split(" ")))

# print(calc(0, n - 1))

arr = [0 for x in range(n)]

arr[1] = abs(initial_vals[0] - initial_vals[1])

for i in range(2, len(arr)):
    arr[i] = min(
        arr[i - 1] + abs(initial_vals[i - 1] - initial_vals[i]),
        arr[i - 2] + abs(initial_vals[i - 2] - initial_vals[i]),
    )

print(arr[n - 1])


import functools
import threading
import sys

class SearchProblem(object):
    def __init__(self, N, H, K):
        self.N = N
        self.H = H
        self.K = K

    def isEnd(self, i):
        return i == self.N

    def succ(self, i):
        return [
            (i + k, abs(self.H[i + k] - self.H[i]))
            for k in range(1, self.K + 1)
            if i + k <= self.N
        ]

def solve(problem: SearchProblem):
    @functools.lru_cache(maxsize=None)
    def future_cost(s):
        if problem.isEnd(s):
            return 0
        else:
            return min(
                cost + future_cost(next_state) for next_state, cost in problem.succ(s)
            )

    return future_cost(1)

def main():
    N, K = [int(x) for x in input().split(" ")]
    H = [None] + [int(x) for x in input().split(" ")]
    problem = SearchProblem(N, H, K)
    print(solve(problem))

if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()

import functools
import threading
import sys

def main():
    @functools.lru_cache(maxsize=None)
    def solve(n):
        if n == 1:
            return 0
        else:
            return min(
                solve(n - k) + abs(H[n] - H[n - k])
                for k in range(1, K + 1)
                if n - k >= 1
            )

    N, K = [int(x) for x in input().split(" ")]
    H = [None] + [int(x) for x in input().split(" ")]
    print(solve(N))

if __name__ == "__main__":

    sys.setrecursionlimit(1024 * 1024 * 2)
    threading.stack_size(128 * 1024 * 1024 * 2)
    threading.Thread(target=main).start()


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

def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    a = [0 for i in range(n)]
    for i in range(1, n):
        a[i] = min([a[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i)])
    print(a[-1])

if __name__ == "__main__":
    main()


import math

N, K = map(int, input().split())
lst = [int(x) for x in input().split()]
dp = [math.inf] * N
dp[0] = 0
dp[1] = abs(lst[0] - lst[1])
for i in range(2, N):
    j = K
    while j > 0:
        if i - j >= 0:
            dp[i] = min(dp[i], dp[i - j] + abs(lst[i - j] - lst[i]))
        j -= 1
print(dp[-1])

import numpy as np

N, K = map(int, input().split())
lst = np.array([int(x) for x in input().split()])
dp = np.zeros(N, dtype=int)

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


import sys

import numba as nb

input = sys.stdin.readline
INF = float("inf")

@nb.njit
def solve(N, K, h):
    dp = [0] * N
    for i in range(1, N):
        min_cost = INF
        for k in range(1, min(K + 1, i + 1)):
            cost = dp[i - k] + abs(h[i] - h[i - k])
            if cost < min_cost:
                min_cost = cost
        dp[i] = min_cost
    return dp[-1]

def main():
    N, K = map(int, input().split())
    h = tuple(map(int, input().split()))

    ans = solve(N, K, h)
    print(ans)

if __name__ == "__main__":
    main()

import sys

import numba as nb
import numpy as np

input = sys.stdin.readline
INF = float("inf")

@nb.njit
def solve(N, K, h):
    dp = [0] * N
    for i in range(1, N):
        min_cost = INF
        for k in range(1, min(K + 1, i + 1)):
            cost = dp[i - k] + abs(h[i] - h[i - k])
            if cost < min_cost:
                min_cost = cost
        dp[i] = min_cost
    return dp[-1]

def main():
    N, K = map(int, input().split())
    h = np.array(input().split(), dtype=np.int64)

    ans = solve(N, K, h)
    print(ans)

if __name__ == "__main__":
    main()

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s994511645.py", line 3, in <module>
    import numba as nb
ModuleNotFoundError: No module named 'numba'


import math

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

dp = [math.inf] * n
dp[0] = 0
for i in range(1, n):
    for j in range(max(0, i - k), i):
        dp[i] = min(dp[i], dp[j] + abs(h[i] - h[j]))
print(dp[n - 1])

import math

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

dp = [math.inf] * n
dp[0] = 0
for i in range(1, n):
    dp[i] = min(dp[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i))
print(dp[n - 1])


import sys

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

def main():
    n, k = map(int, input().split())
    h = list(map(int, input().split()))
    dp = [0] * n
    dp[0] = 0
    dp[1] = abs(h[0] - h[1])

    for i in range(2, n):
        dp[i] = min(abs(h[i] - h[j]) + dp[j] for j in range(max(0, i - k), i))
    print(dp[n - 1])

if __name__ == "__main__":
    main()

import sys
import numpy as np

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

def main():
    n, k = map(int, input().split())
    h = np.array(input().split(), dtype=np.int64)
    dp = np.zeros(n, dtype=np.int64)

    for i in range(1, n):
        j = max(0, i - k)
        dp[i] = np.min(np.abs(h[i] - h[j:i]) + dp[j:i])
    print(dp[n - 1])

if __name__ == "__main__":
    main()


import sys

input = sys.stdin.readline

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

dp = [sys.maxsize] * N

dp[0] = 0

for i in range(1, N):
    s = max(0, i - K)
    dp[i] = min(dp[s:i] + abs(h[s:i] - h[i]))

print(dp[N - 1])

import sys
import numpy as np

input = sys.stdin.readline

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

dp = np.full(N, sys.maxsize, dtype=int)

dp[0] = 0

for i in range(1, N):
    s = max(0, i - K)
    dp[i] = min(dp[s:i] + abs(h[i] - h[s:i]))

print(dp[N - 1])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s304743671.py", line 14, in <module>
    dp[i] = min(dp[s:i] + abs(h[s:i] - h[i]))
TypeError: unsupported operand type(s) for -: 'list' and 'int'


N, K = map(int, input().split())
H = list(map(int, input().split()))
H = [H[0]] * K + H

# dp[i] := 足場iに来るのにかかる最小のコスト
INF = 10**18
dp = [INF] * (K + N)
dp[0] = 0
for i in range(1, N + K):
    for j in range(1, K + 1):
        v = dp[i - j] + abs(H[i] - H[i - j])
        dp[i] = min(dp[i], v)
# print('dp', dp)
ans = dp[-1]
print(ans)

N, K = map(int, input().split())
H = list(map(int, input().split()))
H = [H[0]] * K + H

# dp[i] := 足場iに来るのにかかる最小のコスト
INF = 10**18
dp = [INF] * (K + N)
dp[0] = 0
for i in range(K, N + K):
    h = H[i]
    dp[i] = min(x + abs(y - h) for x, y in zip(dp[i - K : i], H[i - K : i]))
#     for j in range(1, K + 1):
#         v = dp[i - j] + abs(H[i] - H[i - j])
#         dp[i] = min(dp[i], v)
# print('dp', dp)
ans = dp[-1]
print(ans)


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

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

# dp[i] = 足場iに移動するのに必要な最小コスト
dp = [0 for _ in range(N)]

# DP配列更新
for i in range(1, N):
    # 最小コストで更新する
    max_k = min([i, K]) + 1
    dp[i] = min([dp[i - k] + abs(h[i] - h[i - k]) for k in range(1, max_k)])

print(dp[-1])

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np

N, K = map(int, input().split())
h = list(map(int, input().split()))
# 高速化のためにnumpy使う
h = np.array(h)

# dp[i] = 足場iに移動するのに必要な最小コスト
dp = [0 for _ in range(N)]
# 高速化のためにnumpy使う
dp = np.array(dp)

# DP配列更新
"""
TLEだったやつ
for i in range(1, N):
    # 最小コストで更新する
    max_k = min([i, K]) + 1
    dp[i] = min([dp[i - k] + abs(h[i] - h[i - k]) for k in range(1, max_k)])
"""
for i in range(1, N):
    # 最小コストで更新する
    # K個まとめて移動コストを計算することで高速化
    # ただしマイナスからスタートするような値はスキップする
    s = max(0, i - K)
    dp[i] = np.min(dp[s:i] + np.abs(h[s:i] - h[i]))

print(dp[-1])


from math import inf

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
dp = [inf for _ in range(n)]
dp[0] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if i - j >= 0:
            dp[i] = min(dp[i], abs(a[i] - a[i - j]) + dp[i - j])

print(dp[-1])

from math import inf

n, k = map(int, input().split())
a = [int(i) for i in input().split()]
dp = [inf for _ in range(n)]
dp[0] = 0
for i in range(1, n):
    for j in range(1, k + 1):
        if i - j >= 0:
            dp[i] = min(dp[i], abs(a[i] - a[i - j]) + dp[i - j])
        else:
            break

print(dp[-1])


#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation

"""Module docstring
"""

import sys
from collections import deque

def solve(values, nb, max_jump_size):
    max_jump_size = min(nb, max_jump_size)
    cost_to = deque([0])
    new_cost = 0
    for i in range(1, nb):
        new_cost = min(
            cost_to[-k] + abs(values[i] - values[i - k])
            for k in range(1, max_jump_size + 1)
            if i - k >= 0
        )
        if i > max_jump_size:
            cost_to.popleft()
        cost_to.append(new_cost)
    return new_cost

def do_job():
    "Do the work"
    # first line is number of test cases
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    result = solve(values, N, K)
    print(result)

def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))

def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0

if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())

#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation

"""Module docstring
"""

import sys
from collections import deque

def solve(values, nb, max_jump_size):
    max_jump_size = min(nb, max_jump_size)
    cost_to = [0]
    for i in range(1, nb):
        new_cost = min(
            cost_to[i - k] + abs(values[i] - values[i - k])
            for k in range(1, max_jump_size + 1)
            if i - k >= 0
        )
        cost_to.append(new_cost)
    return new_cost

def do_job():
    "Do the work"
    # first line is number of test cases
    N, K = map(int, input().split())
    values = list(map(int, input().split()))
    result = solve(values, N, K)
    print(result)

def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))

def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0

if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())


import sys

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

def main():
    size, jumps = map(int, input().split())
    array = list(map(int, input().split()))
    dp = [999999999] * size
    dp[0] = 0
    dp[1] = abs(array[0] - array[1])
    for i in range(2, size):
        dp[i] = min(
            abs(array[i] - array[j]) + dp[j] for j in range(max(0, i - jumps), i)
        )
    print(dp[size - 1])

if __name__ == "__main__":
    main()


N, K = map(int, input().split())
H = list(map(int, input().split()))
dp = [1 << 62] * N
dp[0] = 0
for i in range(1, N):
    for j in range(i, min(i + 1 + K, N)):
        cost = abs(H[i - 1] - H[i + j])
        dp[i + j] = min(dp[i + j], dp[i - 1] + cost)
print(dp[-1])

N, K = map(int, input().split())
H = list(map(int, input().split()))
dp = [1 << 62] * N
dp[0] = 0
for i in range(1, N):
    for j in range(i, min(i + K, N)):
        cost = abs(H[i - 1] - H[j])
        dp[j] = min(dp[j], dp[i - 1] + cost)
print(dp[-1])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s787574815.py", line 7, in <module>
    cost = abs(H[i - 1] - H[i + j])
IndexError: list index out of range


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

def chmin(num: int, sbn: int):
    dp[num + sbn] = min((dp[num + sbn], dp[num] + abs(h[i + sbn] - h[num])))

for i in range(N):
    for sbn in range(K):
        try:
            chmin(dp, i, sbn + 1)
        except IndexError:
            break
print(dp[-1])

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

def chmin(num: int, sbn: int):
    dp[num + sbn] = min((dp[num + sbn], dp[num] + abs(h[i + sbn] - h[num])))

for i in range(N):
    for sbn in range(K):
        try:
            chmin(i, sbn + 1)
        except IndexError:
            break
print(dp[-1])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03161/Python/s825976309.py", line 15, in <module>
    chmin(dp, i, sbn + 1)
TypeError: chmin() takes 2 positional arguments but 3 were given


#!/usr/bin/env python3

N, K = list(map(int, input().split()))
h_list = list(map(int, input().split()))
dp_list = [float("inf")] * N
dp_list[0] = 0

for i in range(1, N):
    # j番目の足場からi番目の足場に飛ぶ
    min_cost = float("inf")
    for j in range(max(i - K, 0), i):

        # j番目の足場までの最適コスト
        cum_cost = dp_list[j]

        # j番目の足場から飛んだ場合のコスト
        cost = dp_list[j] + abs(h_list[j] - h_list[i])
        if cost < min_cost:
            min_cost = cost

    # 最適コストで更新
    dp_list[i] = min_cost

ans = dp_list[-1]
print(ans)

#!/usr/bin/env python3
import numpy as np

N, K = list(map(int, input().split()))
h_list = list(map(int, input().split()))
h_list = np.array(h_list)
dp_list = np.zeros(N)
dp_list[0] = 0

for i in range(1, N):
    # j番目の足場からi番目の足場に飛ぶ

    min_j = max(i - K, 0)
    cost_list = dp_list[min_j:i] + np.abs(h_list[i] - h_list[min_j:i])
    # 最適コストで更新
    dp_list[i] = np.min(cost_list)

ans = int(dp_list[-1])
print(ans)


import numpy as np

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

#  方針
#  i番目の足場にいるという状態に対して
#  その足場に最も少ないコストを記録する．

dp = np.zeros(n)
for i in range(1, n):
    st = max(0, i - k)
    dp[i] = np.min(dp[st:i] + np.abs(h[i] - h[st:i]))

print(dp[n - 1])

import numpy as np

#  入力
n, k = list(map(int, input().split()))
h = np.array(list(map(int, input().split())))

#  方針
#  i番目の足場にいるという状態に対して
#  その足場に最も少ないコストを記録する．

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

print(dp[-1])


#!/usr/bin/env python3

N, K = list(map(int, input().split()))
h_list = list(map(int, input().split()))
dp_list = [float("inf")] * N
dp_list[0] = 0

for i in range(1, N):
    # j番目の足場からi番目の足場に飛ぶ

    for j in range(max(i - K, 0), i + 1):

        # j番目の足場までの最適コスト
        cum_cost = dp_list[j]

        # j番目の足場から飛んだ場合のコスト
        cost = dp_list[j] + abs(h_list[j] - h_list[i])

        # 最適コストで更新
        dp_list[i] = min(dp_list[i], cost)

ans = dp_list[-1]
print(ans)


n, k, *L = map(int, open(0).read().split())

# dp = [float("inf")] * n
dp = [0] * n

for i in range(1, n):
    j = max(0, i - k)
    dp[i] = min([DP + abs(L[i] - COST) for DP, COST in zip(dp[j:i], L[j:i])])

print(dp[-1])

n, k, *L = map(int, open(0).read().split())

# dp = [float("inf")] * n
dp = [0] * n

for i in range(1, n):
    j = max(0, i - k)
    e = L[i]
    dp[i] = min([DP + abs(e - COST) for DP, COST in zip(dp[j:i], L[j:i])])

print(dp[-1])


# DP(貰うDP)
N, K = map(int, input().split())
h = list(map(int, input().split()))

dp = [0] * N
for i in range(1, N):
    dp[i] = min(dp[j] + abs(h[i] - h[j]) for j in range(max(0, i - K), i))
print(dp[N - 1])

# DP(貰うDP)
def main():
    N, K = map(int, input().split())
    h = list(map(int, input().split()))

    dp = [0] * N
    for i in range(1, N):
        dp[i] = min(dp[j] + abs(h[i] - h[j]) for j in range(max(0, i - K), i))
    print(dp[N - 1])

main()


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

INF = 10**10
dp = [INF] * n
dp[0] = 0
# dp[i] = (足場iにたどり着いた時点でのコストの最小値)

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

print(dp[n - 1])

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

INF = 10**10
dp = [INF] * n
dp[0] = 0
# dp[i] = (足場iにたどり着いた時点でのコストの最小値)

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

print(dp[n - 1])


def main():
    N, K = map(int, input().split())
    h = [0] + list(map(int, input().split()))
    dp = [float("inf") for _ in range(N + 1)]

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

    print(dp[-1])

main()


N, K = map(int, input().split())
hlist = list(map(int, input().split())) + [0] * K
inf = float("inf")
dp = [inf] * (N * K)

def abs_sbn(a, b):
    return abs(hlist[b] - hlist[a])

dp[0] = 0
for i in range(N):
    for j in range(1, K + 1):
        dp[i + j] = min(dp[i + j], dp[i] + abs_sbn(i, i + j))

print(dp[N - 1])

N, K = map(int, input().split())
hlist = list(map(int, input().split())) + [0] * (K + 2)
inf = float("inf")
dp = [inf] * (N * K + 2)

def abs_sbn(a, b):
    return abs(hlist[b] - hlist[a])

dp[0] = 0
for i in range(N):
    for j in range(1, K + 1):
        dp[i + j] = min(dp[i + j], dp[i] + abs_sbn(i, i + j))

print(dp[N - 1])


# dp[i日目][i-1日目にどれを選んだか] = i日目までの最大の幸福度
n = int(input())
a, b, c = [0 for _ in range(n)], [0 for _ in range(n)], [0 for _ in range(n)]
for i in range(n):
    a[i], b[i], c[i] = map(int, input().split())

dp = [[-1 for _ in range(3)] for _ in range(n + 1)]
for i in range(3):
    dp[0][i] = 0

def rec(i, choice):
    if dp[i][choice] > 0:
        return dp[i][choice]
    if i == n:
        return 0
    ret = 0  # ループじゃなくてifでやってるのでそれぞれ確実に大きい値が入る（ので更新する必要がない）
    if choice == 0:
        ret = a[i] + max(rec(i + 1, 1), rec(i + 1, 2))
    elif choice == 1:
        ret = b[i] + max(rec(i + 1, 0), rec(i + 1, 2))
    elif choice == 2:
        ret = c[i] + max(rec(i + 1, 0), rec(i + 1, 1))
    dp[i][choice] = ret
    return ret

print(max(rec(0, 0), rec(0, 1), rec(0, 2)))

# dp[i日目][i-1日目にどれを選んだか] = i日目までの最大の幸福度
import sys

sys.setrecursionlimit(10**8)

n = int(input())
a, b, c = [0 for _ in range(n)], [0 for _ in range(n)], [0 for _ in range(n)]
for i in range(n):
    a[i], b[i], c[i] = map(int, input().split())

dp = [[-1 for _ in range(3)] for _ in range(n + 1)]
for i in range(3):
    dp[0][i] = 0

def rec(i, choice):
    if dp[i][choice] > 0:
        return dp[i][choice]
    if i == n:
        return 0
    ret = 0  # ループじゃなくてifでやってるのでそれぞれ確実に大きい値が入る（ので更新する必要がない）
    if choice == 0:
        ret = a[i] + max(rec(i + 1, 1), rec(i + 1, 2))
    elif choice == 1:
        ret = b[i] + max(rec(i + 1, 0), rec(i + 1, 2))
    elif choice == 2:
        ret = c[i] + max(rec(i + 1, 0), rec(i + 1, 1))
    dp[i][choice] = ret
    return ret

print(max(rec(0, 0), rec(0, 1), rec(0, 2)))


import sys

input = sys.stdin.readline

def chmax(a, b):
    if a > b:
        return a
    else:
        return b

def main():
    N, W = map(int, input().split())
    wv = [None] * N
    for i in range(N):
        wv[i] = tuple(map(int, input().split()))

    dp = [[0] * (W + 1) for _ in range(N + 1)]
    for i, (w, v) in enumerate(wv, start=1):
        dp_i = dp[i]
        dp_im = dp[i - 1]
        for j in range(1, W + 1):
            if j < w:
                dp_i[j] = dp_im[j]
            else:
                dp_i[j] = chmax(dp_im[j - w] + v, dp_im[j])

    ans = dp[-1][-1]
    print(ans)

if __name__ == "__main__":
    main()

import sys

import numba as nb
import numpy as np

input = sys.stdin.readline

@nb.njit("i8(i8, i8)")
def chmax(a, b):
    if a > b:
        return a
    else:
        return b

@nb.njit("i8(i8,i8,i8[:,:])")
def solve(N, W, wv):
    dp = [[0] * (W + 1) for _ in range(N + 1)]
    for i in range(1, N + 1):
        w, v = wv[i - 1]
        for j in range(1, W + 1):
            if j < w:
                dp[i][j] = dp[i - 1][j]
            else:
                dp[i][j] = chmax(dp[i - 1][j - w] + v, dp[i - 1][j])
    return dp[-1][-1]

def main():
    N, W = map(int, input().split())
    wv = np.zeros(shape=(N, 2), dtype=np.int64)
    for i in range(N):
        w, v = map(int, input().split())
        wv[i] = w, v

    ans = solve(N, W, wv)
    print(ans)

if __name__ == "__main__":
    main()


N, W = map(int, input().split())
wv = []
for _ in range(N):
    wv.append(list(map(int, input().split())))
# print(wv)
dp = [[0] * 110 for _ in range(100100)]

for i in range(N):
    for sum_w in range(W + 1):

        if wv[i][0] <= sum_w:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w - wv[i][0]] + wv[i][1])

        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])
print(dp[N][W])

N, W = map(int, input().split())
wv = []
for _ in range(N):
    wv.append(list(map(int, input().split())))
# print(wv)
dp = [[0] * 100100 for _ in range(110)]

for i in range(N):
    for sum_w in range(W + 1):

        if wv[i][0] <= sum_w:
            dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w - wv[i][0]] + wv[i][1])

        dp[i + 1][sum_w] = max(dp[i + 1][sum_w], dp[i][sum_w])
print(dp[N][W])

Traceback (most recent call last):
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03163/Python/s607479372.py", line 6, in <module>
    dp = [[0] * 110 for _ in range(100100)]
  File "/home/alex/Documents/bug-detection/input/Project_CodeNet/data/p03163/Python/s607479372.py", line 6, in <listcomp>
    dp = [[0] * 110 for _ in range(100100)]
MemoryError


import sys

input = sys.stdin.readline

def main():
    N, W = map(int, input().split())
    wv = [None] * N
    for i in range(N):
        wv[i] = tuple(map(int, input().split()))

    dp = [[0] * (W + 1) for _ in range(N + 1)]
    for i, (w, v) in enumerate(wv, start=1):
        dp_i = dp[i]
        dp_im = dp[i - 1]
        for j in range(1, W + 1):
            if j < w:
                dp_i[j] = dp_im[j]
            elif dp_im[j - w] + v > dp_im[j]:
                dp_i[j] = dp_im[j - w] + v
            else:
                dp_i[j] = dp_im[j]

    ans = dp[-1][-1]
    print(ans)

if __name__ == "__main__":
    main()

import sys

input = sys.stdin.readline

def main():
    N, W = map(int, input().split())
    wv = [None] * N
    for i in range(N):
        wv[i] = tuple(map(int, input().split()))

    dp = [[0] * (W + 1) for _ in range(N + 1)]
    for i, (w, v) in enumerate(wv, start=1):
        dp_i = dp[i]
        dp_im = dp[i - 1]
        for j in range(1, W + 1):
            if j < w:
                dp_i[j] = dp_im[j]
            else:
                a = dp_im[j - w] + v
                b = dp_im[j]
                if a > b:
                    dp_i[j] = a
                else:
                    dp_i[j] = b

    ans = dp[-1][-1]
    print(ans)

if __name__ == "__main__":
    main()


import numpy as np

N, W = map(int, input().split())
dp = np.full((N + 1, W + 1), -np.inf, dtype=np.int64)
dp[0][0] = 0
for i in range(N):
    w, v = map(int, input().split())
    for j in range(W + 1):
        dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
        if j + w <= W:
            dp[i + 1][j + w] = max(dp[i + 1][j + w], dp[i][j] + v)
print(max(dp[-1]))

import numpy as np
from numba import njit, i8

@njit(i8(i8, i8, i8[:], i8[:]), cache=True)
def solve(N, W, weights, values):
    dp = np.full((N + 1, W + 1), 0, dtype=np.int64)
    dp[0][0] = 0
    for i in range(N):
        for j in range(W + 1):
            dp[i + 1][j] = max(dp[i + 1][j], dp[i][j])
            if j + weights[i] <= W:
                dp[i + 1][j + weights[i]] = max(
                    dp[i + 1][j + weights[i]], dp[i][j] + values[i]
                )
    return dp[-1].max()

N, W = map(int, input().split())
weights = np.zeros(N, dtype=np.int64)
values = np.zeros(N, dtype=np.int64)
for i in range(N):
    w, v = map(int, input().split())
    weights[i] = w
    values[i] = v
print(solve(N, W, weights, values))


import numpy as np

n, w = map(int, input().strip().split())
data = [list(map(int, input().strip().split())) for _ in range(n)]

# i番目に重さがj以下となるように選んだときの価値の総和の最大値
dp = np.zeros((n, w + 1), dtype=np.int64)

for i in range(0, n):
    for j in range(w + 1):
        # i 番目の品物の重さと価値
        wi, vi = data[i]
        if i == 0:
            take = vi if j - wi >= 0 else 0
            miss = 0
            dp[i][j] = max(take, miss)
        else:
            # i番目の品物を入れる場合
            take = dp[i - 1][j - wi] + vi if j - wi >= 0 else 0
            # 入れない場合
            miss = dp[i - 1][j]
            dp[i][j] = max(take, miss)

print(np.max(dp[n - 1]))

n, w = map(int, input().strip().split())
data = [list(map(int, input().strip().split())) for _ in range(n)]

# i番目に重さがj以下となるように選んだときの価値の総和の最大値
dp = [[0] * (w + 1) for _ in range(n)]

for i in range(0, n):
    for j in range(w + 1):
        # i 番目の品物の重さと価値
        wi, vi = data[i]
        if i == 0:
            take = vi if j - wi >= 0 else 0
            miss = 0
            dp[i][j] = max(take, miss)
        else:
            # i番目の品物を入れる場合
            take = dp[i - 1][j - wi] + vi if j - wi >= 0 else 0
            # 入れない場合
            miss = dp[i - 1][j]
            dp[i][j] = max(take, miss)

print(max(dp[n - 1]))


import numpy as np

n, max_weight = map(int, input().split())
WV = np.array([input().split() for _ in range(n)], np.int64)

W, V = zip(*WV)
dp = np.zeros((n + 1, max_weight + 1), np.int64)

# O(NW)
for i in range(n):
    for w in range(1, max_weight + 1):
        if w >= W[i]:
            dp[i + 1, w] = max(dp[i, w], dp[i, w - W[i]] + V[i])
        else:
            dp[i + 1, w] = dp[i, w]

print(dp[n, max_weight])

n, max_weight = map(int, input().split())
WV = [list(map(int, input().split())) for _ in range(n)]
W, V = zip(*WV)
dp = list([0] * (max_weight + 1) for _ in range(n + 1))
for i in range(n):
    for w in range(1, max_weight + 1):
        if w >= W[i]:
            dp[i + 1][w] = max(dp[i][w], dp[i][w - W[i]] + V[i])
        else:
            dp[i + 1][w] = dp[i][w]

print(dp[n][max_weight])


def knapsack1(weight_value, w):
    cur = [0] * (w + 1)
    nxt = cur.copy()

    for weight, value in weight_value:
        for i in range(1, weight):
            nxt[i] = cur[i]
        for i in range(weight, w + 1):
            nxt[i] = max(cur[i], cur[i - weight] + value)
        cur, nxt = nxt, cur
    return cur[w]

def main():
    n, w = [int(x) for x in input().split()]
    weight_value = [None] * n
    for i in range(n):
        weight_value[i] = [int(x) for x in input().split()]
    return knapsack1(weight_value, w)

print(main())

def knapsack1(weight_value, w):
    cur = [0] * (w + 1)
    nxt = [0] * (w + 1)

    for weight, value in weight_value:
        for i in range(1, weight):
            nxt[i] = cur[i]
        for i in range(weight, w + 1):
            nxt[i] = max(cur[i], cur[i - weight] + value)
        cur, nxt = nxt, cur
    return cur[w]

def main():
    n, w = [int(x) for x in input().split()]
    weight_value = [None] * n
    for i in range(n):
        weight_value[i] = [int(x) for x in input().split()]
    return knapsack1(weight_value, w)

print(main())


"""
AtCoder Educational DP Contest
https://atcoder.jp/contests/dp/tasks/dp_d

D - Knapsack 1
"""
INF = 100000007

def solve(wv_pairs):
    dp = [0] * (W + 1)
    for i in range(N):
        w_i, v_i = wv_pairs[i]
        for ww in range(W, w_i - 1, -1):
            dp[ww] = max(dp[ww], dp[ww - w_i] + v_i)
    return max(dp[ww] for ww in range(W + 1))

N, W = map(int, input().split())
pairs = [[int(s) for s in input().split()] for _ in range(N)]
res = solve(pairs)
print(res)

"""
AtCoder Educational DP Contest
https://atcoder.jp/contests/dp/tasks/dp_d

D - Knapsack 1
"""

def solve(wv_pairs):
    dp = [0] * (W + 1)
    for i in range(N):
        w_i, v_i = wv_pairs[i]
        for ww in range(W, w_i - 1, -1):
            dp[ww] = max(dp[ww], dp[ww - w_i] + v_i)
    return max(dp)

N, W = map(int, input().split())
pairs = [[int(s) for s in input().split()] for _ in range(N)]
res = solve(pairs)
print(res)


N, W = map(int, input().split())
goods = []
for _ in range(N):
    goods.append(tuple(map(int, input().split())))

table = [[0] * (W + 1) for _ in range(N + 1)]
for n in range(N):
    for w in range(W + 1):
        addn = table[n][w - goods[n][0]] + goods[n][1] if w - goods[n][0] >= 0 else 0
        table[n + 1][w] = max(table[n][w], addn)
print(table[N][W])

import numpy as np

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

table = np.zeros((N + 1, W + 1), dtype=np.int64)
for n in range(N):
    tmp = np.zeros(W + 1, dtype=np.int64)
    tmp[goods[n][0] :] = table[n][: W + 1 - goods[n][0]] + goods[n][1]
    table[n + 1] = np.maximum(table[n], tmp)
print(table[N][W])


import numpy as np

#  入力
n, w = map(int, input().split())
wvList = []
wv = np.array([list(map(int, input().split())) for i in range(n)])

#  考えるDPテーブルは
#  重さの総和と使う荷物に関するもの
#  行が重さの上限
#  列が使える荷物の数に相当
dp = np.zeros((w + 1, n + 1), dtype=np.int)
for i in range(1, n + 1):
    #  更新の発想(wに意味はない)
    #  使える荷物が増えたが，利用はしない
    #  dp[w, i] = dp[w, i - 1]
    #  荷物を新しく許可された荷物を使う
    #  dp[w, i] = dp[w - wNew, i-1] + newValue
    #  このうちの価値の大きい方を使う
    dp[:, i] = dp[:, i - 1]
    wNew, vNew = wv[i - 1, 0], wv[i - 1, 1]
    dp[wNew:, :] = np.fmax(dp[wNew:, :], vNew + dp[:-wNew, :])

print(dp[w, n])

import numpy as np

def main():
    N, W = list(map(int, input().split(" ")))
    items = np.array([list(map(int, input().split(" "))) for _ in range(N)])
    dp = np.zeros((N, W + 1))
    dp[0, items[0, 0] :] = items[0, 1]
    for n in range(1, N):
        weight, value = items[n, 0], items[n, 1]
        dp[n, :] = dp[n - 1, :]
        dp[n, weight:] = np.fmax(dp[n, weight:], value + dp[n - 1, :(-weight)])
    print(int(dp[N - 1, W]))

if __name__ == "__main__":
    main()


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

main()

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

main()


#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation

"""Module docstring
"""

import sys

EMPTY = (0, 0, frozenset())

def solve(values, _nb, max_capacity):
    dp = [0] * (max_capacity + 1)
    for w, v in values:
        # dp = dp[:w] + [max(dp[j], dp[j - w] + v) for j in range(w, max_capacity + 1)]
        dp[w:] = [max(dpj, dpjw + v) for dpj, dpjw in zip(dp[w:], dp[:-w])]
    return dp[-1]

def solve_slow(values, nb, max_capacity):
    dp = [[0 for _ in range(max_capacity + 1)] for _ in range(nb + 1)]
    for i in range(1, nb + 1):
        w, v = values[i - 1]
        for j in range(1, max_capacity + 1):
            if w <= j:
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - w] + v)
            else:
                dp[i][j] = dp[i - 1][j]
    # print("\\n".join(map(str, dp)))
    return dp[nb][max_capacity]

def do_job():
    "Do the work"
    # first line is number of test cases
    N, W = map(int, input().split())
    values = []
    for _ in range(N):
        values.append(list(map(int, input().split())))
    result = solve(values, N, W)
    print(result)

def print_output(testcase, result) -> None:
    "Formats and print result"
    if result is None:
        result = "IMPOSSIBLE"
    print("Case #{}: {}".format(testcase + 1, result))

def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    do_job()
    return 0

if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())

# DP
def main():
    N, W = map(int, input().split())

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

main()