Problem:


Score : 500 points

Problem Statement

Ibis is fighting with a monster.

The health of the monster is H.

Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.

The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.

Ibis wins when the health of the monster becomes 0 or below.

Find the minimum total Magic Points that have to be consumed before winning.

Constraints

1 \leq H \leq 10^4

1 \leq N \leq 10^3

1 \leq A_i \leq 10^4

1 \leq B_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 B_1
:
A_N B_N

Output

Print the minimum total Magic Points that have to be consumed before winning.

Sample Input 1

9 3
8 3
4 2
2 1

Sample Output 1

4

First, let us cast the first spell to decrease the monster's health by 8, at the cost of 3 Magic Points. The monster's health is now 1.

Then, cast the third spell to decrease the monster's health by 2, at the cost of 1 Magic Point. The monster's health is now -1.

In this way, we can win at the total cost of 4 Magic Points.

Sample Input 2

100 6
1 1
2 3
3 9
4 27
5 81
6 243

Sample Output 2

100

It is optimal to cast the first spell 100 times.

Sample Input 3

9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461

Sample Output 3

139815



Sample input:
9 3
8 3
4 2
2 1


Sample output:
4

Submission status: Accepted

Solution code:
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7
dir = [(-1,0),(0,-1),(1,0),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

def main():
    h,n = map(int,ipt().split())
    atks = [tuple(map(int,ipt().split())) for i in range(n)]
    dam = [10**18]*(h+1)
    dam[0] = 0
    for i in range(1,h+1):
        for aj,bj in atks:
            if aj > i:
                if dam[i] > bj:
                    dam[i] = bj
            elif dam[i] > dam[i-aj]+bj:
                dam[i] = dam[i-aj]+bj

    print(dam[h])

    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
(h, n), *m = [[*map(int, i.split())] for i in open(0)]
dp = [0] * 20001
for i in range(1, h + 1):
    dp[i] = min(dp[i-a]+b for a, b in m)
print(dp[h])

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
def main():
    H, N = map(int, input().split())
    A = []
    B = []
    for _ in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)
    A_max = max(A)
    dp = [1e14] * (H+A_max + 1) # ダメージ量がiの最小コスト
    dp[0] = 0
    for i in range(H):
        for j in range(N):
            dp[i+A[j]] = min(dp[i+A[j]], dp[i]+B[j])

    ans = 1e30
    for i in range(H, H+A_max+1):
        ans = min(ans, dp[i])
    print(ans)
main()

Submission status: Accepted

Solution code:
h,n = map(int,input().split())
M = []
max_val = 0
for _ in range(n):
    a,b = map(int,input().split())
    max_val = max(max_val,a)
    M.append((a,b))
dp = [float('inf')]*(h+1+max_val)
dp[0] = 0
for i in range(1,h+1+max_val):
    for j in range(n):
            dp[i] = min(dp[i-M[j][0]] + M[j][1],dp[i])
print(min(dp[h:-1]))

Submission status: Accepted

Solution code:
h,n=map(int,input().split())
a=[]
b=[]
for _ in range(n):
  x,y=map(int,input().split())
  a.append(x)
  b.append(y)
a_=max(a)
dp=[10**8]*(h+1+a_)
dp[0]=0
for i in range(1,len(dp)):
  for j in range(n):
    if 0<=i-a[j]<=len(dp)-1-a[j]:
      dp[i]=min(dp[i],dp[i-a[j]]+b[j])
print(min(dp[h:]))

Submission status: Accepted

Solution code:
import numpy as np

h, n = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]
np_ab = np.array(ab)

max_a = max(np_ab[:, 0])
dp = [0] * (h + max_a)

for i in range(1, h + max_a):
    dp[i] = min(dp[i - a] + b for a, b in ab)

print(dp[h])

Submission status: Accepted

Solution code:
import sys

H, N = map(int, input().split())
A = [0] * N
B = [0] * N

for i in range(N):
    a, b = map(int, sys.stdin.readline().rstrip().split())
    A[i] = a
    B[i] = b

max_A = max(A)
INF = 10**18
dp = [INF] * (H + max_A)
dp[0] = 0

for i in range(H):
    for j in range(N):
        dp[i + A[j]] = min(dp[i] + B[j], dp[i + A[j]])

print(min(dp[H:H + max_A]))

Submission status: Accepted

Solution code:
h, n = map(int, input().split())
inf = 10 ** 9
dp = [inf for _ in range(h + 1)]
dp[0] = 0
for _ in range(n):
    a, b = map(int, input().split())
    for i in range(h + 1):
        if i < a:
            dp[i] = min(dp[i], b)
        else:
            dp[i] = min(dp[i], dp[i - a] + b)
print(dp[-1])

Submission status: Accepted

Solution code:
def numba_compile(numba_config):
    import os, sys
    if sys.argv[-1] == "ONLINE_JUDGE":
        from numba import njit
        from numba.pycc import CC
        cc = CC("my_module")
        for func, signature in numba_config:
            vars()[func.__name__] = njit(signature)(func)
            cc.export(func.__name__, signature)(func)
        cc.compile()
        exit()
    elif os.name == "posix":
        exec(f"from my_module import {','.join(func.__name__ for func, _ in numba_config)}")
        for func, _ in numba_config:
            globals()[func.__name__] = vars()[func.__name__]
    else:
        from numba import njit
        for func, signature in numba_config:
            globals()[func.__name__] = njit(signature, cache=True)(func)
        print("compiled!", file=sys.stderr)


import numpy as np

def solve(H, N, AB):
    # dp[n][h] := n 番目の魔法まで見て体力を h 削ったときの最小魔力
    dp = np.empty(H+1, dtype=np.int64)
    dp[:] = 1<<60
    dp[0] = 0
    for n in range(1, N+1):
        a, b = AB[n-1]
        for h in range(H):
            dp[min(H, h+a)] = min(dp[min(H, h+a)], dp[h]+b)
    return dp[-1]

numba_compile([
    [solve, "i8(i8,i8,i8[:,:])"],
])

import sys
def main():
    H, N = map(int, input().split())
    AB = np.array(sys.stdin.read().split(), dtype=np.int64).reshape(N, 2)
    ans = solve(H, N, AB)
    print(ans)

main()

Submission status: Accepted

Solution code:
h, n = map(int, input().split())
a, b = [], []
for _ in range(n):
    A, B = map(int, input().split())
    a.append(A)
    b.append(B)

a_max = max(a)
dp = [0]*(h+a_max)

for i in range(h+a_max):
    dp[i] = min(dp[i-a] + b for a, b in zip(a, b))

print(min(dp[h-1:]))

Submission status: Accepted

Solution code:
import pprint
H, N = list(map(int, input().split()))

A, B = [0]*N, [0]*N


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

maxDamage = H + max(A)

dp = [[float("inf") for _ in range(maxDamage+1)] for _ in range(N+1)]
dp[0][0] = 0

for i in range(N):
    for j in range(maxDamage+1):

        if j < A[i]:
            dp[i+1][j] = dp[i][j]

        else:
            res1 = dp[i][j]
            res2 = dp[i+1][j - A[i]] + B[i]

            dp[i+1][j] = min(res1, res2)

# pprint.pprint(dp)
print(min(dp[N][H:]))

Submission status: Accepted

Solution code:
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8,i8,i8[:,:])", cache=True)
def solve(H, N, AB):
    INF = 10 ** 18
    dp = np.full(shape=(H + 1), fill_value=INF, dtype=np.int64)
    dp[0] = 0
    for i in range(N):
        A, B = AB[i]
        for d in range(H + 1):
            if d < A:
                dp[d] = min(dp[d], B)
            else:
                dp[d] = min(dp[d], dp[d - A] + B)

    ans = dp[-1]
    return ans


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

    ans = solve(H, N, AB)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8,i8,i8[:,:])", cache=True)
def solve(H, N, AB):
    INF = 10 ** 18
    dp = [INF] * (H + 1)
    dp[0] = 0
    for i in range(N):
        A, B = AB[i]
        for d in range(H + 1):
            if d < A:
                dp[d] = min(dp[d], B)
            else:
                dp[d] = min(dp[d], dp[d - A] + B)

    ans = dp[-1]
    return ans


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

    ans = solve(H, N, AB)
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
h,n=map(int,input().split())
a_=0
magic=[]
for i in range(n):
  a,b=map(int,input().split())
  a_=max(a,a_)
  c=[a,b]
  magic.append(c)
dp=[10**8+1]*(h+a_+1)
dp[0]=0
for i in range(n):
  a,b=magic[i]
  for j in range(len(dp)):
    if j+a<=h+a_:
      dp[j+a]=min(dp[j+a],dp[j]+b)
print(min(dp[h:]))

Submission status: Accepted

Solution code:
H,N =[int(i) for i in input().split()]
AAA = []
BBB = []
for i in range(N):
    buff = [int(i) for i in input().split()]
    AAA.append(buff[0])
    BBB.append(buff[1])

#dp[i]は体力をi減らすまでに必要な魔力の最小値
dp = [10000000000 for i in range(H+5)]
dp[0] = 0
for i in range(H+5):
    for j in range(N):
        A = AAA[j]
        B = BBB[j]
        if i-A>=0:
            dp[i]=min(dp[i],dp[i-A]+B)
        else:
            dp[i]=min(dp[i],B)

#print(dp)
print(dp[H])

Submission status: Accepted

Solution code:
from collections import defaultdict
(h,n),*ab = [list(map(int, s.split())) for s in open(0)]

mxa = max(a for a,b in ab)

dp = defaultdict(lambda: float('inf'))
dp[0] = 0

for i in range(1, h+mxa):
    dp[i] = min(dp[i-a] + b for a,b in ab)

print(min(v for k,v in dp.items() if k>=h))

Submission status: Accepted

Solution code:
h,n=map(int,input().split())
INF=10**18
dp=[INF]*(h+1)
dp[0]=0
for _ in range(n):
  a,b=map(int,input().split())
  for i in range(h+1):
    dp[min(i+a,h)]=min(dp[min(i+a,h)],dp[i]+b)
print(dp[h])

Submission status: Accepted

Solution code:
def resolve():
    H, N = list(map(int, input().split()))
    AB = [list(map(int, input().split())) for i in range(N)]
    maxa = max([ab[0] for ab in AB])
    dp = [-1 for _ in range(H+maxa+1)]
    dp[0] = 0
    for i in range(H+1):
        if dp[i] == -1:
            continue
        for a, b in AB:
            dp[i+a] = min(dp[i+a], dp[i]+b) if dp[i+a] != -1 else dp[i]+b
    print(min(filter(lambda x: x != -1, dp[H:])))

    
    
if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
import sys
from fractions import Fraction
input = sys.stdin.readline

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

mp = 0

a = []
b = []

for i in range(n):
    ai, bi = list(map(int, input().split()))
    a.append(ai)
    b.append(bi)

dp = [0] * (h+1)

dp[0] = 0

for i in range(1, h+1):
    m = 1000000000
    for j in range(n):
        l = 0
        if i - a[j] < 0:
            l = b[j]
        else:
            l = b[j] + dp[i - a[j]]
        m = min(l, m)
    dp[i] = m

print(dp[h])

Submission status: Accepted

Solution code:
HP, n_magic = map(int,input().split())
attack_ls, power_taken_ls = [0]*(n_magic+1), [0]*(n_magic+1)
for i in range(n_magic):
    attack_ls[i+1], power_taken_ls[i+1] = map(int,input().split())
max_attack = HP + max(attack_ls)
dp = [[float('inf')]*(max_attack+1) for _ in range(n_magic+1)]
dp[0][0] = 0
for i in range(1,n_magic+1):
    for attack in range(max_attack+1):
        if attack - attack_ls[i] >= 0:
            dp[i][attack] = min(dp[i][attack], dp[i][attack-attack_ls[i]] + power_taken_ls[i])
        dp[i][attack] = min(dp[i-1][attack], dp[i][attack])
ans = float('inf')
for attack in range(HP, max_attack+1):
    ans = min(dp[n_magic][attack], ans)
print(ans)

Submission status: Accepted

Solution code:

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

INF = 10 ** 9 + 7
dp = [[INF] * (H + 1) for _ in range(N + 1)]
dp[0][0] = 0

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

        dp[i + 1][min(j + X[i][0], H)] = min(dp[i + 1][min(j + X[i][0], H)],
                                             dp[i + 1][j] + X[i][1])

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

Submission status: Accepted

Solution code:
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)


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


dp = [0 for i in range(H+1)]

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

print(dp[H])

Submission status: Accepted

Solution code:
H, N = [int(i) for i in input().split()]
M = []
for i in range(N):
  A, B = [int(i) for i in input().split()]
  M.append((A, B))

dp = [0 for i in range(H + 1)]

for i in range(1, H+1):
  cand = []
  for A, B in M:
    cand.append(dp[max(0, i-A)] + B)
  dp[i] = min(cand)
print(dp[H])

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
import math
#from fractions import Fraction
import itertools
from collections import deque
from collections import Counter
import heapq
from fractions  import gcd
#input=sys.stdin.readline
#import bisect
h,n=map(int,input().split())
inf=10**9
ab = [map(int, input().split()) for _ in range(n)]
a,b=[list(i) for i in zip(*ab)]
dp=[[inf]*(h+1) for _ in range(n+1)]
dp[0][0]=0
for i in range(n):
    for j in range(h+1):
        dp[i+1][j]=min(dp[i+1][j],dp[i][j])
        dp[i+1][min(h,j+a[i])]=min(dp[i+1][min(h,j+a[i])],dp[i+1][j]+b[i])
print(dp[-1][-1])

Submission status: Accepted

Solution code:
h, n = map(int, input().split())
xs = [0] * n
for i in range(n):
    xs[i] = list(map(int, input().split()))

dp = [10 ** 9] * (h + 1)
dp[0] = 0
for i in range(h):
    for j in range(n):
        x = min(i + xs[j][0], h)
        dp[x] = min(dp[x], dp[i] + xs[j][1])
print(dp[h])

Submission status: Accepted

Solution code:
import sys

H, N = map(int, input().split())
ABs = [(0,0)]

for _ in range(N):
  a,b = map(int, input().split())
  ABs.append((a,b))
  
memo = [[sys.maxsize]*(H+1) for _ in range(N+1)]
memo[0][H] = 0

for i in range(1,N+1):
  for j in range(H,0,-1):
    if j + ABs[i][0] <= H:
      memo[i][j] = min(memo[i-1][j], memo[i][j+ ABs[i][0]] + ABs[i][1])
    else:
      memo[i][j] = min(memo[i][j], memo[i-1][j])
    if j - ABs[i][0] <= 0:
      memo[i][0] = min(memo[i-1][0], memo[i][0], memo[i][j]+ABs[i][1])
      
print(memo[N][0])

Submission status: Accepted

Solution code:
(h,n),*c=[[*map(int,i.split())]for i in open(0)]
d=[0]*20002
for i in range(h):d[i]=min(d[i-a]+b for a,b in c)
print(d[h-1])

Submission status: Accepted

Solution code:
(h,n),*c=[[*map(int,i.split())]for i in open(0)]
dp=[0]*20002
for i in range(h):dp[i]=min(dp[i-a]+b for a,b in c)
print(dp[h-1])

Submission status: Accepted

Solution code:
#import sys
#sys.setrecursionlimit(10**9)

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

for k in range(N):
  magic[k] = list(map(int, input().split()))
  magic[k].append(magic[k][0]/magic[k][1])

magic.sort(key = lambda x: x[2], reverse=True)
ans = [0 for _ in range(H+1)]
visited = [0]
anskouho = [float('inf')]
ans2 = float('inf')
"""
def solve(start, power, point, maryoku):
  if start == H:
    print(min(point, min(anskouho)))
    exit()
  elif start > H:
    anskouho.append(point)
    return 0
  elif ans[start] != 0:
    return 0
  else:
    visited.append(start)
    ans[start] = point
    solve(start+power, power, point+maryoku, maryoku)
"""
for k in range(N):
  for item in visited:
    #solve(item+magic[k][0], magic[k][0], ans[item] + magic[k][1], magic[k][1])
    start = item+magic[k][0]
    power = magic[k][0]
    point = ans[item]+ magic[k][1]
    maryoku = magic[k][1]
    for _ in range(10**5):
      if start == H:
        print(min(point, ans2))
        exit()
      elif start > H:
        ans2 = min(ans2, point)
        break
      elif ans[start]!=0:
        break
      else:
        visited.append(start)
        ans[start] = point
        start += power
        point += maryoku
      
print(ans2)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

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

for k in range(N):
  magic[k] = list(map(int, input().split()))
  magic[k].append(magic[k][0]/magic[k][1])

magic.sort(key = lambda x: x[2], reverse=True)
ans = [0 for _ in range(H+1)]
visited = [0]
anskouho = [float('inf')]

def solve(start, power, point, maryoku):
  if start == H:
    print(min(point, min(anskouho)))
    exit()
  elif start > H:
    anskouho.append(point)
    return 0
  elif ans[start] != 0:
    return 0
  else:
    visited.append(start)
    ans[start] = point
    solve(start+power, power, point+maryoku, maryoku)

for k in range(N):
  for item in visited:
    solve(item+magic[k][0], magic[k][0], ans[item] + magic[k][1], magic[k][1])

print(min(anskouho))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

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

for k in range(N):
  magic[k] = list(map(int, input().split()))
  magic[k].append(magic[k][0]/magic[k][1])

magic.sort(key = lambda x: x[2], reverse=True)
ans = [0 for _ in range(H+1)]
visited = [0]
anskouho = [float('inf')]

def solve(start, power, point, maryoku):
  if start == H:
    print(min(point, min(anskouho)))
    exit()
  elif start > H:
    anskouho.append(point)
    #visited.sort(reverse=True)
    return 0
  elif ans[start] != 0:
    #visited.sort(reverse=True)
    return 0
  else:
    visited.append(start)
    ans[start] = point
    solve(start+power, power, point+maryoku, maryoku)

for k in range(N):
  for item in visited:
    solve(item+magic[k][0], magic[k][0], ans[item] + magic[k][1], magic[k][1])

print(min(anskouho))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)

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

for k in range(N):
  magic[k] = list(map(int, input().split()))
  magic[k].append(magic[k][0]/magic[k][1])

magic.sort(key = lambda x: x[2], reverse=True)
ans = [0 for _ in range(H+1)]
visited = [0]
anskouho = [float('inf')]

def solve(start, power, point, maryoku):
  if start == H:
    print(min(point, min(anskouho)))
    exit()
  elif start > H:
    anskouho.append(point)
    visited.sort(reverse=True)
    return 0
  elif ans[start] != 0:
    visited.sort(reverse=True)
    return 0
  else:
    visited.append(start)
    ans[start] = point
    solve(start+power, power, point+maryoku, maryoku)

for k in range(N):
  for item in visited:
    solve(item+magic[k][0], magic[k][0], ans[item] + magic[k][1], magic[k][1])

print(min(anskouho))

Submission status: Accepted

Solution code:
H, N = map(int, input().split())
AB = []
for _ in range(N):
    A, B = map(int, input().split())
    AB.append([A, B])
AB = sorted(AB, key=lambda x:x[0], reverse=True)
INF = float("inf")
dp = [INF for _ in range(H+1)]
dp[0] = 0

# DP
for i in range(1, H+1):
    for a, b in AB:
        if a >= i:
            dp[i] = min(dp[i], b)
            continue
        else:
            dp[i] = min(dp[i], dp[i-a]+b)
print(dp[-1])

Submission status: Accepted

Solution code:
import math


def read_int():
    return int(input().strip())


def read_ints():
    return list(map(int, input().strip().split(' ')))


def solve():
    H, N = read_ints()
    A, B = [], []
    for _ in range(N):
        a, b = read_ints()
        A.append(a)
        B.append(b)
    OPT = [math.inf for _ in range(H+max(A)+1)]
    OPT[0] = 0
    for h in range(H):
        for i in range(N):
            OPT[h+A[i]] = min(OPT[h+A[i]], OPT[h]+B[i])
    return min(OPT[H:])


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

Submission status: Accepted

Solution code:
(h,n),*t=[[*map(int,t.split())]for t in open(0)]
d=[0]*9**8
for i in range(h):d[i+1]=min(b+d[i-a+1]for a,b in t)
print(d[h])

Submission status: Accepted

Solution code:
h,n=map(int,input().split())
ans=0
magic=[]
al=[]
bl=[]
for i in range(n):
  a,b=map(int,input().split())
  magic.append([a,b])
  al.append(a)
  bl.append(b)
amx=max(al)
bmn=min(bl)
dp=[-1]*(h+amx+1)
dp[0]=0
for i in range(1,h+amx+1):
  mn=float("inf")
  for j in magic:
    mp=j[1]
    at=j[0]
    if at>i:
      cst=mp
    else:
      cst=dp[i-at]+mp
    if cst<mn:
      mn=cst
  dp[i]=mn
  
print(min(dp[h:]))

Submission status: Accepted

Solution code:
def coin(larger=False, single=False):
    """
    ナップサックに入れる重さが W 丁度になる時の価値の最小値
    :param larger: False = (重さ = W)の時の最小価値
                   True  = (重さ =< W)の時の最小価値
    :param single: False = 重複あり

    dp[weight <= W+1] = 重さを固定した時の最小価値
    dp[W+1] = 重さがWより大きい時の最小価値
    """
    W2 = W + 1              # dp[W+1] に W より大きい時の全ての場合の情報を持たせる
    dp_max = float("inf")   # 総和価値の最大値
    dp = [dp_max] * (W2 + 1)
    dp[0] = 0               # 重さ 0 の時は価値 0

    for item in range(N):
        if single:
            S = range(W2, weight_list[item] - 1, -1)
        else:
            S = range(W2)
        for weight in S:
            dp[min2(weight + weight_list[item], W2)] = min2(dp[min2(weight + weight_list[item], W2)], dp[weight] + cost_list[item])
    if larger:
        return min(dp[w] for w in range(W, W2+1))
    else:
        return dp[W]

#######################################################################################################
import sys
input = sys.stdin.readline


def max2(x, y):
    return x if x > y else y

def min2(x, y):
    return x if x < y else y

W, N = map(int, input().split())                                # N: 品物の種類 W: 重量制限

cost_list = []
weight_list = []
for _ in range(N):
    """ cost と weight が逆転して入力されている場合有り """
    weight, cost = map(int, input().split())
    cost_list.append(cost)
    weight_list.append(weight)


print(coin(larger=True, single=False))

Submission status: Accepted

Solution code:
def knapsack_weight(single=True):
    """
    重さが小さい時のナップサックDP
    :param single: True = 重複なし
    """
    """ dp[weight <= W] = 重さを固定した時の最小価値 """
    weight_max = max(weight_list)
    price_max = max(price_list)
    W2 = W + weight_max
    dp_max = float("inf")  # 総和価値の最大値
    dp = [dp_max] * W2
    dp[0] = 0               # 重さ 0 の時は価値 0

    for item in range(N):
        if single:
            S = range(W2, weight_list[item] - 1, -1)
        else:
            S = range(weight_list[item], W2)
        for weight in S:
            dp[weight] = min2(dp[weight], dp[weight - weight_list[item]] + price_list[item])
    return min(dp[w] for w in range(W, W2))

#######################################################################################################
import sys
input = sys.stdin.readline


def max2(x, y):
    """ pythonの組み込み関数 max は2変数に対しては遅い！！ """
    if x > y:
        return x
    else:
        return y

def min2(x, y):
    """ pythonの組み込み関数 min は2変数に対しては遅い！！ """
    if x < y:
        return x
    else:
        return y


W, N = map(int, input().split())                                # N: 品物の種類 W: 重量制限

price_list = []
weight_list = []
for _ in range(N):
    """ price と weight が逆転して入力されている場合有り """
    weight, price = map(int, input().split())
    price_list.append(price)
    weight_list.append(weight)


print(knapsack_weight(single=False))


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

Submission status: Accepted

Solution code:
(h,n),*t=[list(map(int,o.split()))for o in open(0)]
d=[0]*10**8
for i in range(h):d[i+1]=min(b+d[i-a+1]for a,b in t)
print(d[h])

Submission status: Accepted

Solution code:
(h,n),*t=[list(map(int,o.split()))for o in open(0)]
d=[0]*(h+9999)
for i in range(1,h+1):d[i]=min(d[i-a]+b for a,b in t)
print(d[h])

Submission status: Accepted

Solution code:
(h,n),*t=[list(map(int,o.split()))for o in open(0)]
d=[0]*(h+10100)
for i in range(1,h+1):d[i]=min(d[i-a]+b for a,b in t)
print(d[h])

Submission status: Accepted

Solution code:
(h,n),*t=[map(int,o.split())for o in open(0)]
d=[0]+[9e9]*h
for a,b in t:
 for j in range(h+1):d[j]=min(d[j],d[max(0,j-a)]+b)
print(d[h])

Submission status: Accepted

Solution code:
def chmin(dp, i, *x):
  dp[i] = min(dp[i], *x)
INF = float("inf")

# dp[i] := min 消耗する魔力 to H -= i
h, n = map(int, input().split())
dp = [0] + [INF]*h
for _ in [None]*n:
  a, b = map(int, input().split())
  for j in range(h + 1):
    chmin(dp, min(j + a, h), dp[j] + b)
print(dp[h])

Submission status: Accepted

Solution code:
from math import ceil
h, n = map(int, input().split())
data = []
for i in range(n):
    a, b = map(int, input().split())
    data.append([a, b])

max_a = max(a for a, b in data)
dp = [0] * (h + max_a)
for i in range(h + max_a):
    dp[i] = min(dp[i - a] + b for a, b in data)

print(min(dp[h - 1: ]))

Submission status: Accepted

Solution code:
H,N=map(int,input().split())
A=[]
B=[]
for i in range(N):
    n,a=input().split()
    A.append(int(n))
    B.append(int(a))
def f(x):
    if x<=0:
        return 0
    else:
        mini=g(x-A[0])+B[0]
        for i in range (1,N):
            sub=g(x-A[i])+B[i]
            if sub<mini:
                mini=sub
        return mini
def g(x):
    if x<0:
        return 0
    else:
        return g_list[x]
g_list=[]
g_list.append(0)
for i in range(1,H+1):
    g_list.append(f(i))
print(g_list[-1])

Submission status: Accepted

Solution code:
from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

h, n = MAP()
a = [0]*n
b = [0]*n
dp = [inf]*(h+1)
dp[0] = 0
# dp[j]: ダメージ>=jとするために必要な魔力の最小値

for i in range(n):
    a[i], b[i] = MAP()

for i in range(n):
    for j in range(0,h+1):
        if j < a[i]:
            dp[j] = min(dp[j], b[i])
        else:
            dp[j] = min(dp[j], dp[j-a[i]]+b[i])

print(dp[h])

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()

def main():
    h,n=map(int, input().split())
    ab=[list(map(int, input().split())) for i in range(n)]
    ans=[0]*(4*10**4)
    for i in range(1,h+1):
        li = [ans[i-j[0]]+j[1] for j in ab]
        ans[i]=min(li)
    print(ans[h])

if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
import numpy as np
h, n = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]
np_ab = np.array(ab)
max_a = max(np_ab[:, 0])
dp = [0]*(h+max_a)
for i in range(1, h+max_a):
    dp[i] = min(dp[i-a] + b for a,b in ab)
print(dp[h])

Submission status: Accepted

Solution code:
H, N = map(int, input().split())
spells = []
for i in range(N):
  A, B = map(int, input().split())
  spells.append({"attack":A, "cost":B})

# O(HN)
dp = [0]
for i in range(H):
  dp.append(2147483648)
  
for h in range(H):
  for spell in spells:
    index = min(h+spell["attack"], H)
    current_min_mp = dp[index] 
    new_mp = dp[h] + spell["cost"]
    if (new_mp < current_min_mp):
      dp[index] = new_mp

print(dp[-1])

Submission status: Accepted

Solution code:
INF = 1 << 60

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

MAX = h - 1 + max(a)
dp = [[INF for j in range(MAX + 1)] for i in range(n)]
dp[0][0] = 0
if 0 <= a[0] < MAX + 1:
    dp[0][a[0]] = b[0]
for j in range(MAX + 1):
    if 0 <= j - a[0] < MAX + 1:
        dp[0][j] = min(dp[0][j], dp[0][j - a[0]] + b[0])
for i in range(1, n):
    for j in range(MAX + 1):
        dp[i][j] = min(dp[i][j], dp[i - 1][j])
        if 0 <= j - a[i] < MAX + 1:
            dp[i][j] = min(dp[i][j], dp[i][j - a[i]] + b[i])
ans = INF
for j in range(h, MAX + 1):
    ans = min(ans, dp[-1][j])
print(ans)

Submission status: Accepted

Solution code:
H,N = map(int,input().split())
INF = 10 ** 10
dp = [INF] * (H + 1)
dp[0] = 0

for i in range(N):
  attack,magic = map(int,input().split())
  for j in range(len(dp)):
    if dp[j] == INF:
      continue
    target = j + attack
    if j + attack > H:
      target = H
    if dp[target] > dp[j] + magic:
      dp[target] = dp[j] + magic
      
print(dp[-1])

Submission status: Accepted

Solution code:
def solve():
    H,N = map(int,input().split())
    ap = []
    mp = []

    for _ in range(N):
        a,b = map(int,input().split())
        ap.append(a)
        mp.append(b)
    
    ap_max = max(ap)
    
    dp = [[float('inf')] * (H+ap_max+1) for _ in range(N+1)]
    for i in range(N+1):
        dp[i][0] = 0
    
    for i in range(N):
        for sum_h in range(H+ap_max+1):
            if sum_h - ap[i] >= 0:
                dp[i+1][sum_h] = min(dp[i][sum_h-ap[i]] + mp[i], dp[i][sum_h])
                dp[i+1][sum_h] = min(dp[i+1][sum_h-ap[i]] + mp[i], dp[i][sum_h])
            dp[i+1][sum_h] = min(dp[i+1][sum_h], dp[i][sum_h])
    
    ans = float('inf')
    for sum_h in range(H, H+ap_max+1):
        ans = min(ans,dp[N][sum_h])

    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
def solve():
    H,N = map(int,input().split())
    ap = []
    mp = []

    for _ in range(N):
        a,b = map(int,input().split())
        ap.append(a)
        mp.append(b)
    
    ap_max = max(ap)
    
    dp = [[float('inf')] * (H+ap_max+1) for _ in range(N+1)]
    for i in range(N+1):
        dp[i][0] = 0
    
    for i in range(N):
        for sum_h in range(H+ap_max+1):
            dp[i+1][sum_h] = min(dp[i][sum_h-ap[i]] + mp[i], dp[i][sum_h])
            dp[i+1][sum_h] = min(dp[i+1][sum_h-ap[i]] + mp[i], dp[i][sum_h])
    
    ans = float('inf')
    for sum_h in range(H, H+ap_max+1):
        ans = min(ans,dp[N][sum_h])

    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
a=[]
dp=[float("inf") for i in range(1+10**4)]
h,n=map(int,input().split())
for i in range(n):
    A,B=map(int,input().split())
    a.append((A,B))
dp[0]=0
for i in range(1+10**4):
    for A,B in a:
        dp[i]=min(dp[i],dp[max(0,i-A)]+B)
print(dp[h])

Submission status: Accepted

Solution code:
h,n= map(int, input().split())
p = [list(map(int, input().split())) for _ in range(n)] 
m = 10**4
dp = [0]*(h+m+1)
for i in range(m+1,h+m+1):
  dp[i] = min(dp[i-a] + b for a,b in p)
print(dp[h+m])

Submission status: Accepted

Solution code:

def resolve():
    INF = 1<<60
    H, N = map(int, input().split())
    A, B = [], []
    for i in range(N):
        a, b = map(int, input().split())
        A.append(a)
        B.append(b)

    dp = [[INF]*(H+1) for _ in range(N+1)]
    for i in range(N):
        dp[i][0] = 0
    
    for i in range(N):
        for j in range(H+1):
            if j < A[i]:
                # 体力がマイナスなっても魔法は使用できる
                dp[i + 1][j] = min(dp[i][j], B[i])
            else:
                dp[i + 1][j] = min(dp[i][j], dp[i + 1][j - A[i]] + B[i])

    print(dp[N][H])


if __name__ == "__main__":
    resolve()