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: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import copy
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


def solve():
    H, N = Scanner.map_int()
    A, B = [0] * N, [0] * N
    for i in range(N):
        A[i], B[i] = Scanner.map_int()
    INF = 10 ** 10
    dp = [INF for _ in range(H + 1)]
    dp[0] = 0
    for i in range(H + 1):
        for j in range(N):
            k = max(0, i - A[j])
            dp[i] = min(dp[i], dp[k] + B[j])
    print(dp[H])


def main():
    # sys.setrecursionlimit(1000000)
    # sys.stdin = open("sample.txt")
    solve()


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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: Time Limit Exceeded

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    H, N = NMI()
    M = [NLI() for _ in range(N)]
    # dp[i] はiダメージ与えたときの最小の魔力
    dp = [10**10] * (H+10)
    dp[0] = 0
    for i in range(H):
        for m in M:
            dp[min(i+m[0], H)] = min(dp[min(i+m[0], H)], dp[i] + m[1])
    print(dp[H])



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H,N=map(int,input().split())
AB=np.zeros([N,2]).astype(int)
for i in range(N):AB[i,:] = list(map(int,input().split()))

dp = np.zeros([H+AB[:,0].max()+1, N+1]).astype(int)
for j in range(1,H+1):
  for i in range(1,N+1):
    if AB[i-1,0] < j:
      dp[j,i] = dp[j - AB[i-1,0], i] + AB[i-1,1]
    else:
      dp[j,i] = AB[i-1,1]
  dp[j,1:] = dp[j,1:].min()

print(dp[H,1:].min())

Submission status: Time Limit Exceeded

Solution code:
HP, n = map(int, input().split())
AB = [list(map(int,input().split())) for _ in range(n)]

# DP
## DP[i]は、モンスターにダメージ量iを与えるのに必要な魔力の最小コスト
## DPの初期化
DP = [float('inf')] * (HP+1); DP[0] = 0
## HP分だけDPを回す.
for now_hp in range(HP):
    ## 全ての魔法について以下を試す.
    for damage, cost in AB:
        ### 与えるダメージは、現在のダメージ量＋魔法のダメージか体力の小さい方
        next_hp = min(now_hp+damage, HP)
        ### 今の魔法で与えるダメージ量に必要な最小コストは、->
        ####->現在わかっている値か今のHPまでの最小コスト＋今の魔法コストの小さい方
        DP[next_hp] = min(DP[next_hp], DP[now_hp]+cost)
print(DP[-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
H,N=map(int,input().split())
AB=np.zeros([N,2]).astype(int)
for i in range(N):AB[i,:] = list(map(int,input().split()))

dp = np.zeros([H+AB[:,0].max()+1, N+1]).astype(int)
for j in range(1,H+AB[:,0].max()+1):
  for i in range(1,N+1):
    if AB[i-1,0] < j:
      dp[j,i] = dp[j - AB[i-1,0], 1:].min() + AB[i-1,1]
    else:
      dp[j,i] = AB[i-1,1]

print(dp[H,1:].min())

Submission status: Time Limit Exceeded

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)
    dp[0] = 0

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

    print(dp[H])


if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

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()

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
min2 = lambda x,y: x if x < y else y
H,N = map(int,input().split())

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

AB.sort(key=lambda x: x[1]/x[0])

cost = [(float('inf'),float('inf'))]*(H+1)
last = [0]*(H+1)

q = [((0,0), 0)]

while q:
    cli, t = heappop(q)
    if cost[t] <= cli:
        continue
    cost[t] = cli
    if t == H:
        break

    c,li = cli
    for i,(a,b) in enumerate(AB[li:], start=li):
        d = min2(H,t+a)
        if cost[d] > (c+b,i):
            heappush(q, ((c+b, i), d))

print(cost[H][0])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop
min2 = lambda x,y: x if x < y else y
H,N = map(int,input().split())

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

AB.sort(key=lambda x: -x[1])

cost = [float('inf')]*(H+1)
last = [None]*(H+1)

q = [(0, 0)]

while q:
    c, t = heappop(q)
    if cost[t] <= c:
        continue
    cost[t] = c
    if t == H:
        break
    if last[t] is None:
        for i,(a,b) in enumerate(AB):
            d = min2(H,t+a)
            if cost[d] > c+b:
                last[d] = i
                heappush(q, (c+b, d))
            if cost[d] == c+b:
                last[d] = min2(last[d], i)
    else:
        for i,(a,b) in enumerate(AB[last[t]:]):
            d = min2(H,t+a)
            if cost[d] > c+b:
                last[d] = i
                heappush(q, (c+b, d))
            if cost[d] == c+b:
                last[d] = min2(last[d], i)

print(cost[H])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop

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

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

cost = [float('inf')]*(H+1)

q = [(0, 0)]

while q:
    c, t = heappop(q)
    if cost[t] <= c:
        continue
    cost[t] = c
    if t == H:
        break
    for a,b in AB:
        d = min(H,t+a)
        if cost[d] > c+b:
            heappush(q, (c+b, d))

print(cost[H])

Submission status: Time Limit Exceeded

Solution code:
from heapq import heappush, heappop

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

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

cost = [float('inf')]*(H+1)

q = [(0, 0)]

while q:
    c, t = heappop(q)
    if t >= H:
        cost[H] = c
        break
    if cost[t] <= c:
        continue

    cost[t] = c
    for a,b in AB:
        heappush(q, (b+c, t+a))

print(cost[H])

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

# 個数制限なしナップサック問題
W,N = map(int,readline().split())

dp = [INF for j in range(W+1)]
dp[0] = 0

for i in range(N):
    w,v = map(int,readline().split())
    # dp[j] = 重さj以下でつくれる最大の価値
    for j in range(W+1):
        dp[j] = min(dp[j],dp[max(j-w,0)] + v)

print(dp[W])

Submission status: Time Limit Exceeded

Solution code:
h,n = map(int,input().split())
inf = 1000000000
res = inf
dp = [inf] * (h + 1)
dp[0] = 0
for i in range(n):
    a,b = map(int,input().split())
    for j in range(h):
        to = min(j + a,h)
        dp[to] = min(dp[to],dp[j] + b)
print(dp[h])

Submission status: Time Limit Exceeded

Solution code:
h,n = map(int,input().split())
lst = [list(map(int,input().split())) for _ in range(n)]
inf = 1000000000
res = inf
dp = [inf] * (h + 1)
dp[0] = 0
for a,b in lst:
    for j in range(h):
        to = min(j + a,h)
        dp[to] = min(dp[to],dp[j] + b)
print(dp[h])

Submission status: Time Limit Exceeded

Solution code:
H, N = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(N)]

INF = 10 ** 9
dp = [INF] * (H+1)
dp[0] = 0
for i in range(H):
    for j in range(N):
        idx = min(H, i+ab[j][0])
        dp[idx] = min(dp[idx], dp[i]+ab[j][1])
print(dp[-1])

Submission status: Time Limit Exceeded

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


def main():
  H, N = list(map(int, input().split()))
  A = [0]*N
  B = [0]*N
  for i in range(N):
    A[i], B[i] = map(int, input().split())

  dp = [[0]*(H+1) for _ in range(N+1)]
  for j in range(H+1):
    dp[0][j] = float('inf')
  dp[0][0] = 0

  for i in range(1, N+1):
    for j in range(1, H+1):
      dp[i][j] = dp[i-1][j]
      if j > A[i-1]:
        dp[i][j] = min(dp[i][j], dp[i][j-A[i-1]]+B[i-1])
      else:
        dp[i][j] = min(dp[i][j], B[i-1])

  # for i in range(N+1):
  #   print(dp[i])
  print(dp[N][H])


if(__name__ == '__main__'):
  main()

Submission status: Time Limit Exceeded

Solution code:
h,n = map(int,input().split())
magic = [ list(map(int,input().split())) for i in range(n)]
INF = float("inf")

dp =  [[INF]*(h+1) for i in range(n+1)]

"""
i番目までの魔法の中から攻撃力の合計が
jを超えるように選んだときの消費精神力の最小値
"""

for i in range(n):
    for j in range(h):
        if j < magic[i][0]:#その魔法で一撃
             dp[i+1][j+1] = min(dp[i][j+1],magic[i][1])
        elif j >= magic[i][0] and 0<= j+1-magic[i][0] <= h:
            dp[i+1][j+1] = min(dp[i][j+1],dp[i][j+1-magic[i][0]]+magic[i][1],dp[i+1][j+1-magic[i][0]]+magic[i][1])#その魔法を連打したときが考慮されていない
        
print(dp[n][h])

Submission status: Time Limit Exceeded

Solution code:
import math

# H, N = 9, 3
# ARR = [
#     [8, 3],
#     [4, 2],
#     [2, 1]
# ]
#
#
# H, N = 100, 6
# ARR = [
#     [1, 1],
#     [2, 3],
#     [3, 9],
#     [4, 27],
#     [5, 81],
#     [6, 243]
# ]
#

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

for i in range(N):
    ARR.append(list(map(int, input().split())))


def calculate(h, n, arr):
    brr = [math.inf] * (h+1)
    brr[0] = 0

    for i in range(h + 1):
        for j in range(n):

            damage = arr[j][0]
            cost = arr[j][1]

            nextDamage = i + damage

            if nextDamage > h:
                nextDamage = h

            nextCost = min(brr[i] + cost, brr[nextDamage])

            brr[nextDamage] = nextCost

    print(brr[-1])


calculate(H, N, ARR)

Submission status: Time Limit Exceeded

Solution code:
import math

# H, N = 9, 3
# ARR = [
#     [8, 3],
#     [4, 2],
#     [2, 1]
# ]
#
#
# H, N = 100, 6
# ARR = [
#     [1, 1],
#     [2, 3],
#     [3, 9],
#     [4, 27],
#     [5, 81],
#     [6, 243]
# ]
#

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

for i in range(N):
    ARR.append(list(map(int,input().split())))


def calculate(h, n, arr):
    brr = []
    for i in range(h + 1):
        brr.append(math.inf)

    brr[0] = 0

    for i in range(h + 1):
        for j in range(n):

            damage = arr[j][0]
            cost = arr[j][1]

            nextDamage = i + damage

            if nextDamage > h:
                nextDamage = h

            nextCost = min(brr[i]+cost, brr[nextDamage])

            brr[nextDamage] = nextCost

    print(brr[-1])


calculate(H, N, ARR)

Submission status: Time Limit Exceeded

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

dp = [INF]*(H+1)
dp[0] = 0

for _ in range(N):
  a, b = map(int, input().split())
  AB.append((a, b))

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

print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
def main():
    INF = 10 ** 10
    H, N = list(map(int, input().split(' ')))
    magic = [list(map(int, input().split(' '))) for _ in range(N)]
    MAX_A = max(list(map(lambda x: x[0], magic)))
    dp = [INF for _ in range(MAX_A + H + 1)]
    dp[0] = 0
    for h in range(1, MAX_A + H + 1):
        for i in range(N):
            a, b = magic[i]
            if h - a < 0:
                continue
            dp[h] = min(dp[h], b + dp[h - a])
    print(min(dp[H:]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
H,n = readInts()
A = []
B = []
for i in range(n):
    a,b = readInts()
    A.append(a)
    B.append(b)
# dp[h][i] := 体力 h の時の、魔法i番目を使った時の魔力の最小値
# dp[h] でいいかもこれ
INF = float('inf')
dp = [INF] * (H+1)
dp[0] = 0
for h in range(0,H+1):
    for i in range(n):
        dp[min(h+A[i],H)] = min(dp[min(h+A[i],H)], dp[h] + B[i])

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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

def main():
    H, N = map(int, input().split())
    A = [None] * N
    B = [None] * N
    for i in range(N):
        A[i], B[i] = map(int, input().split())

    #1次元DPに書き換え
    INF = 10**12
    dp = [INF] * (H+1)
    dp[0] = 0
    for i in range(N):
        for j in range(H+1):
            dp[min(j+A[i],H)] = min(dp[min(j+A[i],H)],dp[j]+B[i])
    print(dp[H])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import deque, Counter
from heapq import heappop, heappush
from bisect import bisect_right

def main():
    H, N = map(int, input().split())
    A = [None] * N
    B = [None] * N
    for i in range(N):
        A[i], B[i] = map(int, input().split())

    INF = 10**12
    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(j+A[i],H)] = min(dp[i+1][min(j+A[i],H)],dp[i+1][j]+B[i])
    print(dp[N][H])

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
H, N = map(int, input().split())
Magic = [list(map(int, input().split())) for i in range(N)]
MAX_COST = max(Magic)[1]
 
# dp[damage] := モンスターに damage を与えるために必要な最小コスト
dp = [float('inf')] * (H + 1)
dp[0] = 0
for h in range(H):
    for damage, cost in Magic:
        next_index = min(h + damage, H)
        dp[next_index] = min(dp[next_index], dp[h] + cost)
print(dp[-1])

Submission status: Time Limit Exceeded

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

import numpy as np

dp = np.full((n+1, h+1), 10**10)
dp[0][0]=0
for i in range(0,n):
  damage = magics[i][0]
  cost = magics[i][1]
  for j in range(0,h+1):
    dp[i+1][j] = min( dp[i+1][j], dp[i][j] )

    to = min( j+damage, h )
    dp[i+1][to] = min( dp[i+1][j]+cost, dp[i+1][to] )
                                                 
print(dp[n][h])

Submission status: Time Limit Exceeded

Solution code:
def solve():
    H, N = map(int, input().split())
    A = [list(map(int, input().split())) for _ in range(N)]
    dp = [float('inf')]*(H+10**4)
    dp[0] = 0
    for h in range(1,H+10**4):
        for i in range(N):
            if A[i][0]<=h:
                dp[h] = min(dp[h],dp[h-A[i][0]]+A[i][1])
    ans = min(dp[H:])
    return ans
print(solve())

Submission status: Time Limit Exceeded

Solution code:
h, n = map(int, input().split())

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


dp = [10**9 for i in range((h+1)+10000)]
dp[0] = 0
for i in range(1, (h+1)+10000):
  for j in range(n):
    a, b = ab[j]
    if a > i:
      continue
    dp[i] = min(dp[i], dp[i-a]+b)

x = min(dp[h:])
print (x)

Submission status: Time Limit Exceeded

Solution code:
h, n = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]

dp = [float('inf')] * (h+1)
dp[0] = 0

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

Submission status: Time Limit Exceeded

Solution code:
H, N = map(int, input().split())
A = []
max_A = 0
for i in range(N):
    A.append(tuple(map(int, input().split())))
    max_A = max(max_A, A[i][0])

INF = 10**9
dp = [INF] * (2 * 10 ** 4 + 1)
dp[0] = 0

for i in range(2 * 10 ** 4):
    for a, b in A:
        if i + a <= 2 * 10 ** 4:
            dp[i+a] = min(dp[i]+b, dp[i+a])

print(min(dp[H:]))

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
# https://tane-no-blog.com/851/ より
import sys
input = sys.stdin.buffer.readline
import numpy as np

def main():
    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[i]: モンスターの体力を i 減らすための消耗の最小値
    # 素朴にはh(体力)だけでよさそうだが，オーバーキルの可能性がある
    # →max_a(魔法の強さの最大値)も足しておく
    dp = [0]*(h+max_a)

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

    # 体力を削りきった中で最小の消耗を出力
    print(min(dp[h:]))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# https://tane-no-blog.com/851/ より
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[i]: モンスターの体力を i 減らすための消耗の最小値
# 素朴にはh(体力)だけでよさそうだが，オーバーキルの可能性がある
# →max_a(魔法の強さの最大値)も足しておく
dp = [0]*(h+max_a)

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

# 体力を削りきった中で最小の消耗を出力
print(min(dp[h:]))

Submission status: Time Limit Exceeded

Solution code:
import sys
readline = sys.stdin.readline
INF = 10 ** 8


def main():
    H, N = map(int, readline().rstrip().split())
    dp = [INF] * (H + 1)  # HPを減らすのに必要な最小のMP
    dp[0] = 0

    for _ in range(N):
        hp, mp = map(int, readline().rstrip().split())

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

    print(dp[-1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    H, N = il()
    magic = [il() for _ in range(N)]
    dp = [0] * (H + 1)

    dp[0] = 0
    for h in range(1, H + 1):
        for n in range(N):
            if n == 0:
                if magic[n][0] <= h:
                    dp[h] = dp[h - magic[n][0]] + magic[n][1]
                else:
                    dp[h] = magic[n][1]
            else:
                if magic[n][0] <= h:
                    dp[h] = min(dp[h], dp[h - magic[n][0]] + magic[n][1])
                else:
                    dp[h] = min(dp[h], magic[n][1])
    print(dp[-1])


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

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

Submission status: Time Limit Exceeded

Solution code:
h,n= map(int, input().split())
p = []
for i in range(n):
  z = list(map(int, input().split()))
  p.append(z)
dp = [0]*(h+1)
for i in range(1,h+1):
  q = []
  for j in p:
    q.append(dp[max(0,i-j[0])]+j[1])
  dp[i] = min(q)
print(dp[h])

Submission status: Time Limit Exceeded

Solution code:
H, N, *AB = map(int, open(0).read().split())
A = AB[::2]
B = AB[1::2]

dp = [float("inf")] * (H + 1)
dp[0] = 0

for i in range(N):
    for h in range(H):
        dec_health = min(h + A[i], H)
        dp[dec_health] = min(dp[dec_health], dp[h] + B[i])
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
H, N, *AB = map(int, open(0).read().split())
A = []
B = []
for a, b in zip(*[iter(AB)] * 2):
    A.append(a)
    B.append(b)

dp = [float("inf")] * (H + 1)
dp[0] = 0

for i in range(N):
    for h in range(H):
        dec_health = min(h + A[i], H)
        dp[dec_health] = min(dp[dec_health], dp[h] + B[i])
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
INF = 10**10

h, n = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(n)]
dp = [INF]*(h+1)
dp[0] = 0
for i in range(n):
  a, b = AB[i]
  for j in range(h+1):
    if j <= a:
      dp[j] = min(dp[j], b)
    else:
      dp[j] = min(dp[j], dp[j-a]+b)
print(dp[h])

Submission status: Time Limit Exceeded

Solution code:
def main():
    h, n = list(map(int, input().split()))
    A, B = [], []
    for _ in range(n):
        a, b = list(map(int, input().split()))
        A.append(a)
        B.append(b)
    mx = max(A)
    mn = min(A)
    INF = float('inf')
    dp = [INF] * (h + mx + 1)
    dp[0] = 0
    for i in range(1, h + mx + 1):
        res = []
        for a, b in zip(A, B):
            if i - a < 0:
                res.append(b)
            else:
                res.append(dp[i - a] + b)
        dp[i] = min(res)
    print(min(dp[h:h + mx + 1]))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def fact(N):
        res = {}
        tmp = N
        for i in range(2, int(N ** 0.5 + 1) + 1):
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            if cnt > 0:
                res[i] = cnt
        if tmp != 1:
            res[tmp] = 1
        if res == {}:
            res[N] = 1
        return res


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    H, N = Scanner.map_int()
    A = [0 for _ in range(N)]
    B = [0 for _ in range(N)]
    for i in range(N):
        A[i], B[i] = Scanner.map_int()
    dp = [INF for _ in range(10 ** 4 + 10)]
    dp[0] = 0
    for i in range(H + 1):
        for n in range(N):
            dp[i] = min(dp[i], dp[max(0, i - A[n])] + B[n])
    print(dp[H])


def main():
    # sys.stdin = open("sample.txt")
    # T = Scanner.int()
    # for _ in range(T):
    #     solve()
    # print('YNeos'[not solve()::2])
    solve()


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from collections import deque
from functools import lru_cache
import bisect
import re
import queue
import decimal


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [Scanner.string() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [Scanner.int() for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True

    @staticmethod
    def fact(N):
        res = {}
        tmp = N
        for i in range(2, int(N ** 0.5 + 1) + 1):
            cnt = 0
            while tmp % i == 0:
                cnt += 1
                tmp //= i
            if cnt > 0:
                res[i] = cnt
        if tmp != 1:
            res[tmp] = 1
        if res == {}:
            res[N] = 1
        return res


def pop_count(x):
    x = x - ((x >> 1) & 0x5555555555555555)
    x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
    x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
    x = x + (x >> 8)
    x = x + (x >> 16)
    x = x + (x >> 32)
    return x & 0x0000007f


MOD = int(1e09) + 7
INF = int(1e15)


def solve():
    H, N = Scanner.map_int()
    L = Scanner.int_list_list(N)
    dp = [0 for _ in range(10 ** 7 + 10)]
    i = 0
    while True:
        for n in range(N):
            x = i - L[n][1]
            if x >= 0:
                dp[i] = max(dp[i], dp[x] + L[n][0])
        if dp[i] >= H:
            print(i)
            return
        i += 1


def main():
    # sys.stdin = open("sample.txt")
    # T = Scanner.int()
    # for _ in range(T):
    #     solve()
    # print('YNeos'[not solve()::2])
    solve()


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

for i in range(N):
    A, B = map(int, (input().split()))
    for j in range(1, H + 1):
        dp[i][j] = min(dp[i - 1][j], dp[i][max(j - A, 0)] + B)

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

Submission status: Time Limit Exceeded

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

dp = [0] * (H + 1)
for i in range(1, H + 1):
    dp[i] = min([dp[i - A[n]] + B[n] if i >= A[n] else B[n] for n in range(N)])

print(dp[-1])