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:
#E
import numpy as np
H, N = map(int, input().split())
a = []
b = []
a.append(10**9)
b.append(10**9)

for i in range(N):
    a_i, b_i = map(int, input().split())
    a.append(a_i)
    b.append(b_i)

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

a = np.array(a)
b = np.array(b)

#b *= -1

for i in range(N+1):
    dp[i][0] = b[i]
#for j in range(H+1):
#    dp[0][j] = 10**9
dp[0][:] = 10**9

#print(dp)

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

#print(dp)
#print('ans')
#print(dp)
print(int(dp[N][H]))

Submission status: Time Limit Exceeded

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

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], x[1]))

cost = [-1 for i in range(H + 1)]


def f(H):
    c = []
    for damage, mp_cost in AB:
        tmp = H - damage
        if tmp <= 0:
            c.append(mp_cost)
            continue
            break
        if cost[tmp] != -1:
            c.append(cost[tmp] + mp_cost)
        else:
            cost[tmp] = f(tmp)
            c.append(cost[tmp] + mp_cost)
    return min(c)


# print('H', H)
# print('f(H)', f(H))
print(f(H))
# print('after cost', cost)

Submission status: Time Limit Exceeded

Solution code:
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)

dp = [float('inf') for i in range(H+max(A))]
dp[0] = 0

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

print(min(dp[H:]))

Submission status: Time Limit Exceeded

Solution code:
import sys
H, N = map(int, input().split())
AB = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
dp = [float('inf') for _ in range(H+1)]

for i, ab in enumerate(AB):
    a, b = ab
    for j in range(H // AB[i][0] + 2):
        dp[min(AB[i][0] * j, H)] = min(dp[min(AB[i][0] * j, H)], AB[i][1] * j)
        j += 1

for h in range(H):
    for n in range(N):
        for j in range((H - h) // AB[n][0] + 2):
            dp[min(h + AB[n][0] * j, H)] = min(dp[min(h + AB[n][0] * j, H)], dp[h] + AB[n][1] * j)
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import math

H, N = map(int, input().split())
damage= []
cost = []
for i in range(N):
  a,b = map(int, input().split())
  damage.append(a)
  cost.append(b)
  
damage=np.array(damage)
cost=np.array(cost)
E = damage/cost
best = E.argmax() 

ma= math.ceil(H/damage[best]) * cost[best]
count = np.array([0]*N)
count[best] = math.ceil(H/damage[best])

def search(count, damage, cost, E, H):
  at= count.argmax()
  count[at] = count[at]-1
  n= len(count)
  tmp_c_lists =[count]*n
  sum_list = np.array([0]*n)

  for i in range(n):
    while True:
      tmp_c_lists[i][i] == tmp_c_lists[i][i]+1
      if np.sum(tmp_c_lists[i]* damage) >= H:
        break
    sum_list[i] = np.sum(cost*tmp_c_lists[i])
    arg = np.argmin(sum_list)
  return np.sum(tmp_c_lists[arg]* damage)

while True:
  new = search(count, damage, cost, E, H)
  if ma <= new:
    break
  else:
    ma =new
print(ma)

Submission status: Time Limit Exceeded

Solution code:
import unittest


class TestE(unittest.TestCase):
    def test_1(self):
        self.assertEqual(think(9, [[8, 3], [4, 2], [2, 1]]), 4)

    def test_2(self):
        self.assertEqual(think(100, [[1, 1], [2, 3], [3, 9], [4, 27], [5, 81], [6, 243]]), 100)

    def test_3(self):
        self.assertEqual(think(
            9999,
            [
              [540, 7550], [691, 9680], [700, 9790],
              [510, 7150], [415, 5818], [551, 7712],
              [587, 8227], [619, 8671], [588, 8228],
              [176, 2461]
            ]
        ), 139815)


def solve():
    h, list_of_a_and_b = read()
    result = think(h, list_of_a_and_b)
    write(result)


def read():
    h, n = read_int(2)
    list_of_a_and_b = []
    for _ in range(n):
        list_of_a_and_b.append(read_int(2))
    return h, list_of_a_and_b


def read_int(n):
    return read_type(int, n, sep=' ')


def read_float(n):
    return read_type(float, n, sep=' ')


def read_type(t, n, sep):
    return list(map(lambda x: t(x), read_line().split(sep)))[:n]


def read_line(n=0):
    if n == 0:
        return input().rstrip()
    else:
        return input().rstrip()[:n]


def think(h, list_of_a_and_b):
    min_of_a = 1
    max_of_b = 10 ** 4
    max_of_h = 10 ** 4
    inf = (max_of_h // min_of_a) * max_of_b + 1

    dp = [[inf for _ in range(h + 2)] for _ in range(max_of_h + 1)]
    dp[0][0] = 0

    # dp[i][max]; i is count of usage of magic; max is max of damage
    # dp[i][max] = minimum sum of magic power

    min_cost = inf

    for i in range(1, max_of_h + 1):
        for j in range(h + 2):
            if dp[i - 1][j] == inf:
                continue
            for a, b in list_of_a_and_b:
                if j + a >= len(dp[0]):
                    dp[i][h + 1] = min(dp[i][h + 1], dp[i - 1][j] + b)
                else:
                    dp[i][j + a] = min(dp[i][j + a], dp[i - 1][j] + b)
                min_cost = min(min_cost, dp[i][h], dp[i][h + 1])

    return min_cost


def write(result):
    print(result)


if __name__ == '__main__':
    # unittest.main()
    solve()

Submission status: Time Limit Exceeded

Solution code:
H, N = [int(x) for x in input().split()]
A = []
B = []
dp = [[float("infinity") for _ in range(H+1)] for _ in range(N+1)]


def solve():
    for i in range(N):
        a, b = [int(x) for x in input().split()]
        for h in range(H+1):
            dp[i+1][h] = min(dp[i][h], (dp[i+1][h-a] if h - a > 0 else 0) + b)
    return dp


dp = solve()
print(dp[N][H])

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import numpy as np


DEBUG = True
dprint = print if DEBUG else lambda *x : x

H, N = [int(str) for str in input().strip().split()]
AB = [[int(str) for str in input().strip().split()] for _ in range(N)]

dp = [0]
for h in range(1, H + 1):
    dp.append(min([i[1] + dp[max(0, h - i[0])] for i in AB]))
    
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
H, N = [int(x) for x in input().split()]
A = []
B = []
dp = [[float("infinity") for _ in range(H+1)] for _ in range(N+1)]


def solve():
    for i in range(N):
        dp[i][0] = 0

    for i in range(N):
        a, b = [int(x) for x in input().split()]
        for h in range(H+1):
            dp[i+1][h] = min(dp[i][h], (dp[i+1][h-a] if h - a > 0 else 0) + b)
    return dp


dp = solve()
print(dp[N][H])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from math import ceil
from copy import copy

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

def func(magic):
    dp = np.ones(H + magic[:,0].max() * 2 + 1) * np.inf
    dp[0] = 0

    for i in range(0, H+1):
        if dp[i] == np.inf:
            continue
        
        for m in magic:
            dp[i+m[0]] = min(dp[i+m[0]], dp[i] + m[1])

    print(int(dp[H:].min()))



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

    magic = np.array(magic)
    func(magic)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

b_max = 10**100
dp = [b_max] * (h+1)
dp[0] = 0
for i in range(1, h+1):
  old = list(dp)
  for j in range(n):
    a, b = m[j]
    he = max(0, i - a)
    dp[i] = min(dp[i], b + old[he], dp[he] + b)
print(dp[h])

Submission status: Time Limit Exceeded

Solution code:
import sys
from functools import lru_cache

sys.setrecursionlimit(1000000)

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

AB = []
for i in range(N):
  A, B = map(int, input().split())
  AB.append((A, B))

'''
H = 10000
N = 1000
import random
AB = []
for i in range(N):
    A = random.randint(1, 10000)
    B = random.randint(1, 10000)
    AB.append((A, B))
'''




@lru_cache(maxsize=None)
def f(h):
    if h <= 0:
        return 0
    return min(b + f(h - a) for a, b in AB)

#AB.sort(key=lambda ab: (ab[0] / ab[1], -ab[0]))
#bestA, bestB = AB[-1]

bestA, bestB = max(AB, key=lambda ab: (ab[0] / ab[1], -ab[0]))
threshold = sum(a for a, b in AB)

ans = None
times = (H - threshold) // bestA
if times > 0:
    ans = bestB * times + f(H - bestA * times)
else:
    ans = f(H)

print(ans)

Submission status: Time Limit Exceeded

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

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[2], x[0]))
# print('AB', AB)

cost = [-1 for i in range(H + 1)]
# for damage, mp_cost in AB:
#     cost[damage] = mp_cost
# print('cost', cost)

# c = []
# for damage, mp_cost in AB:


def f(H):
    c = []
    for damage, mp_cost in AB:
        tmp = H - damage
        if tmp <= 0:
            c.append(mp_cost)
            continue
        if cost[tmp] != -1:
            c.append(cost[tmp] + mp_cost)
        else:
            cost[tmp] = f(tmp)
            c.append(cost[tmp] + mp_cost)
    return min(c)


# print('H', H)
# print('f(H)', f(H))
print(f(H))
# print('after cost', cost)

Submission status: Time Limit Exceeded

Solution code:
import sys

input = sys.stdin.readline

ri = lambda: int(input())
rs = lambda: input().rstrip()
ril = lambda: list(map(int, input().split()))
rsl = lambda: input().rstrip().split()
ris = lambda n: [ri() for _ in range(n)]
rss = lambda n: [rs() for _ in range(n)]
rils = lambda n: [ril() for _ in range(n)]
rsls = lambda n: [rsl() for _ in range(n)]

h, n = ril()
ls = rils(n)
dp = [float('inf')] * (h + 1)
dp[0] = 0
for i, (a, b) in enumerate(ls):
    for j in range(h + 1):
        dp[min(j + a, h)] = min(dp[min(j + a, h)], dp[j] + b)
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
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)
d = {}

sys.setrecursionlimit(10000000)

def toki(h, n):
    if (h, n) in d.keys():
        return d[(h, n)]
    else:
        if h <= 0:
            d[(h, n)] = 0
            return d[(h, n)]
        elif n == 1:
            d[(h, n)] = toki(h - A[0], 1) + B[0]
            return d[(h, n)]
        else:
            d[(h, n)] = min(toki(h, n - 1), toki(h - A[n-1], n) + B[n-1])
            return d[(h, n)]

print(toki(h, n))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
H,N=map(int,input().split())

cost=[]
for _ in range(N):
    A,B=map(int,input().split())
    cost.append([A/B,A,B])
"""
mx=0
mi=10**12
ind=-1
for index,item in enumerate(cost):
    mx=max(mx,item[0])
    if mx==item[0] and mi>item[1]:
        ind=index

ans=0
temp=cost[ind][1]
ans+=H//(temp)*cost[ind][2]

H-=temp*(H//temp-1)
"""

dp=[10**12]*H
dp[0]=0
sans=10**12
for item in cost:
    for i in range(len(dp)):
        if dp[i]!=10**12:
            if i+item[1]>=H:
                sans=min(sans,dp[i]+item[2])
            else:
                dp[i+item[1]]=min(item[2]+dp[i],dp[i+item[1]])
    
print(sans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
hp, n = map(int,input().split())

list = np.zeros((n,2),dtype=int)
for i in range(n):
    list[i][0], list[i][1] = map(int,input().split())

dp = np.full((n+1, hp+1), 100000000000000000,dtype=int)

dp[0][0] = 0
for i, lista in enumerate(dp):
    dp[i][0] = 0
    for j, value in enumerate(lista):
        if i == 0:
            continue
        if j < list[i-1][0]:
            dp[i][j] = min(list[i-1][1], dp[i-1][j])
        else:
            target = j - list[i-1][0]
            dp[i][j] = min((dp[i][target] + list[i-1][1]), dp[i-1][j])

print(int(dp[n][hp]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def main():
    H,N = map(int, input().split())
    weight = list(); value = list()
    for n in range(N):
        temp = input().split()
        weight.append(int(temp[0]))
        value.append(int(temp[1]))
    
    inf = float("inf")
    dp = np.zeros([N+1, H+max(weight)+1])
    for i in range(N+1):
        for j in range(H+max(weight)+1):
            dp[i,j] = inf
    for i in range(N+1): dp[i,0] = 0
    for i in range(N):
        for h in range(H+max(weight)+1):
            if(weight[i] <= h):
                dp[i+1,h]=min(dp[i,h-weight[i]]+value[i], dp[i+1,h-weight[i]]+value[i], dp[i,h])
            else:
                dp[i+1,h]=dp[i,h]
    res = int(min(dp[N][H:]))
    print(res)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8

def main():
    h, n = map(int, input().split())
    ab = []
    for _ in range(n):
        ab.append(list(map(int, input().split())))
    
    inf = 100000000000
    # indexがモンスターに与えたダメージで、中身がトキのダメージ
    damages = [inf for _ in range(100000)]
    damages[0] = 0
    pre_damage = -1
    for i in range(h):
        if damages[i] == inf:
            continue
        for j in range(n):
            new_damage = ab[j][0]
            if damages[i + new_damage] > damages[i] + ab[j][1]:
                damages[i + new_damage] = damages[i] + ab[j][1]
        

    print(min(damages[h:]))
main()

Submission status: Time Limit Exceeded

Solution code:
h,n=map(int,input().split())
M=[]
maxA=0
for i in range(n):
    a,b=map(int,input().split())
    M.append([a,b])
    maxA=max(maxA,a)

dp=[-1]*(h+maxA+5)
dp[0]=0
for i in range(1,h+maxA+5):
    for m in range(n):
        hp=M[m][0]
        mp=M[m][1]
        if i>=hp and dp[i-hp]!=-1: #体力より多い かつ 前の参照が存在しているとき
            if dp[i]==-1: #まだ更新されてないとき
                dp[i]=dp[i-hp]+mp
            else: #既に値があるとき
                dp[i]=(min(dp[i],dp[i-hp]+mp))

chk=h
while dp[chk]==-1:
    chk+=1
ans=dp[chk]
for i in range(chk+1,h+maxA+5):
    if dp[i]!=-1:
        ans=min(ans,dp[i])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

### TESTCASE
test = ""
#test = \
"""
9 3
8 3
4 2
2 1
ans 4
"""

"""
5 2
4 4
2 3
ans 7
"""

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

"""
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
ans 139815
"""
############
test = list(reversed(test.strip().splitlines()))
if test:
    def input2():
        return test.pop()
else:
    def input2():
        return input()
####### MAIN
        
h, n = map(int, input2().split())    
ab = [tuple(map(int, input2().split())) for _ in range(n)]

dp = [0] * (h + 1)

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

Submission status: Time Limit Exceeded

Solution code:
H,N = map(int, input().split())
dp_ = [0]+[float("inf")]*H
for n in range(N):
  dp = [0]+[float("inf")]*H
  A,B = map(int, input().split())
  for h in range(1,H+1):
    h_ = max(0,h-A)
    dp[h] = min(dp_[h], dp[h_]+B)
  dp_ = dp
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
H, N = map(int, input().split())
A_list = []
B_list = []
for i in range(N):
    A, B = map(int, input().split())
    A_list.append(A)
    B_list.append(B)

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

for i in range(1, H + 1):
    min_ij = 10 ** 9
    for j in range(N):
        A = A_list[j]
        B = B_list[j]
        min_ij = min(min_ij, (dp[i - A] if i >= A else 0) + B)
    dp[i] = min(dp[i], min_ij)

print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
inf = 10**18
H,N = map(int,input().split())
AB = [list(map(int,input().split())) for _ in range(N)]
dp = [[inf]*(N+1) for _ in range(H+1)]
for h in range(H+1):
    for i in range(N+1):
        if i > 0 and h - AB[i - 1][0] > 0:
            dp[h][i] = min(dp[h][i-1], dp[h-AB[i-1][0]][i] + AB[i-1][1])
        elif i > 0:
            dp[h][i] = min(dp[h][i-1], AB[i-1][1])

print(dp[H][N])

Submission status: Time Limit Exceeded

Solution code:
H, N = map(int, input().split())
A= [(list(map(int, input().split()))) for _ in range(N)]
total_point = 0
 
while H > 0:
	B= [a[0]/a[1] for a in A]
	
print(total_point)

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') for _ in range(H+1)]

for i, ab in enumerate(AB):
    a, b = ab
    for j in range(H // AB[i][0] + 2):
        dp[min(AB[i][0] * j, H)] = min(dp[min(AB[i][0] * j, H)], AB[i][1] * j)
        j += 1

for h in range(H):
    for n in range(N):
        for j in range((H - h) // AB[n][0] + 2):
            dp[min(h + AB[n][0] * j, H)] = min(dp[min(h + AB[n][0] * j, H)], dp[h] + AB[n][1] * j)
print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
H,N=map(int,input().split())
ABC=[]
for _ in range(N):
  a,b=map(int,input().split())
  ABC.append((a,b,a/b))
ABC=sorted(ABC, key=lambda x:x[2], reverse=True)
A=[ABC[i][0] for i in range(N)]
B=[ABC[i][1] for i in range(N)]
dp=[[float('inf')]*(H+1) for i in range(N+1)]
for i in range(N+1):
  dp[i][0]=0
  
for i in range(N):
  for j in range(1,H+1):
    if j-A[i]>=0:
      dp[i+1][j]=min(dp[i][j],dp[i+1][j-A[i]]+B[i])
    else:
      dp[i+1][j]=min(dp[i][j],dp[i+1][0]+B[i])
print(dp[N][H])
#print(dp)

Submission status: Time Limit Exceeded

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

A = []
B = []
for _ in range(N):
    i1,i2 = map(int,input().split())
    A.append(i1)
    B.append(i2)


# HPが0のとき
dp = {}
# 全てコスト無限大としておく
for hp in range(H+1):
    dp[hp] = float('inf')

dp[H] = 0
for hp in range(H,-1,-1):
    # 遷移 = 魔法を1つ使う
    for i in range(N):
        # 遷移先
        hp_next = hp - A[i]
        if hp_next < 0: hp_next = 0
        # 遷移先のコスト
        mp_next = dp[hp] + B[i]
        

        dp[hp_next] = min(dp[hp_next],mp_next)

print(dp[0])

Submission status: Time Limit Exceeded

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

def solve(ab, hp, memo):
  if hp <= 0:
    return 0
  else:
    ans = 10**10
    if not hp in memo:
      for attack, cost in ab:
        ans = min(ans, solve(ab, hp-attack, memo)+cost)
      memo[hp] = ans
    return memo[hp]

H, N = map(int, input().split())
AB = [list(map(int, input().split())) for _ in range(N)]
print(solve(AB, H, {}))

Submission status: Time Limit Exceeded

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

mins = [10**10]*(h+1)
mins[0] = 0
ind = 0
while ind < h:
    for a, b in magics:
        target = min(h, ind+a)
        mins[target] = min(b + mins[ind], mins[target])
    ind += 1
    while True:
        if mins[ind] < 10**10 and min(mins[ind:])==mins[ind]:
            break
        ind += 1
print(mins[h])

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

H,N = map(int,readline().split())
m = map(int,read().split())
AB = zip(m,m)

INF = 10 ** 18
dp = [INF] * (20000)
dp[0] = 0

for a,b in AB:
    for n in range(H):
        if dp[n+a] > dp[n] + b:
            dp[n+a] = dp[n] + b

answer = min(dp[H:])
print(answer)

Submission status: Time Limit Exceeded

Solution code:
H, N = (int(x) for x in input().split())

spells = []
for _ in range(N):
    a, b = (int(x) for x in input().split())

    spells.append((a,b))

costs = [0] * (H+1)
for i in range(1, H+1):
    costs[i] = min(b + costs[max(0, i-a)] for a,b in spells)

print(costs[-1])

Submission status: Time Limit Exceeded

Solution code:
from math import floor
import numpy as np

H, N = map(int, input().split())
A, B = np.zeros(N, dtype='int'), np.zeros(N, dtype='int')
for i in range(N):
    a, b = map(int, input().split())
    A[i] = a
    B[i] = b

dp = np.zeros(H, dtype='int')
# dp[h-1] は、体力hのモンスターを倒すのにかかる最小コスト
minimum_cost_magic = np.argmin(B)
minA, minB = A[minimum_cost_magic], B[minimum_cost_magic]
dp[:minA] = minB
for h in range(minA, H):
    # dp[h] を求める i.e. 体力h+1のモンスターを倒すのにかかる最小コスト
    mincost = 1e8
    for mj in range(N):
        dp_minusAmj = dp[h - A[mj]] if h - A[mj] >= 0 else 0
        if dp_minusAmj + B[mj] < mincost:
            mincost = dp_minusAmj + B[mj]
    dp[h] = mincost

print(dp[H-1])

Submission status: Time Limit Exceeded

Solution code:
H, N = list(map(int, input().split()))
ab_list = []
max_a = -float("inf")
for _ in range(N):
    a, b = list(map(int, input().split()))
    ab_list.append((a, b))
    max_a = max(max_a, a)

dp_table = [[0] + [float("inf")] * (H + max_a) for _ in range(N + 1)]

for i in range(1, N + 1):
    a, b = ab_list[i - 1]
    next_j = 0
    for j in range(H + max_a):
        # 攻撃jをしない場合
        before_best_cost = dp_table[i - 1][j]
        dp_table[i][j] = before_best_cost
        # 攻撃jをする場合
        if j - a < 0:
            continue
        cost = dp_table[i - 1][j - a] + b
        min_cost = min(before_best_cost, cost)

        cost = dp_table[i][j - a] + b
        min_cost = min(min_cost, cost)

        dp_table[i][j] = min_cost

        if j > H and min_cost != float("inf"):
            dp_table[i][H] = min(dp_table[i][H], min_cost)

ans = dp_table[-1][H]
print(ans)

Submission status: Time Limit Exceeded

Solution code:
H, N = map(int, input().split())
#Cost=[]
#for i in range(N):
#  A, B = map(int, input().split())
#  Cost.append([A, B])
Cost=[[int(x) for x in input().split()] for _ in range(N)]
#  Cost.append((A, B, A/B))
#Cost = sorted(Cost, key=lambda row: row[0], reverse=True)
#sortedCost = sorted(Cost, key=lambda row: row[2], reverse=True)
#print(Cost)

DP=[float('inf')]*(H+2)
DP[0]=0
DP[1]=0
for i in range(2,H+2):
    for j in range(N):
      if i-Cost[j][0]>=0:
          DP[i]=min(DP[i], DP[i-Cost[j][0]]+Cost[j][1])
      else:
          DP[i]=min(DP[i], Cost[j][1])

print(DP[H+1])

Submission status: Time Limit Exceeded

Solution code:
def resolve():
    h, n = map(int, input().split())
    w = []
    v = []
    for i in range(n):
        a, b = map(int, input().split())
        w.append(a)
        v.append(b)
    dp = [[0 for i in range(h + 1)] for j in range(n + 1)]
    for i in range(1, h + 1):
        # dp[0][i] = v[0] * ((w[0]+i-1)//w[0])
        dp[0][i] = float("inf")
    for i in range(n):
        # print(dp[i])
        # print(dp[i][::-1][::w[i]]+[0])
        for j in range(h + 1):
            if j >= w[i]:
                dp[i + 1][j] = min([x + y * v[i]
                                    for y, x in enumerate(dp[i][:j+1][::-1][::w[i]]+[0])])
            else:
                dp[i + 1][j] = min(dp[i][j], v[i])
    # print(dp[n])
    print(dp[n][h])


if __name__ == '__main__':
    resolve()

Submission status: Time Limit Exceeded

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)

mA = max(A)

INF = 1001001001
DP = [INF for _ in range(H+1)]
DP[0] = 0
ans = INF
for h in range(H):
    for j in range(N):
        DP[min(h+A[j], H)] = min(DP[min(h+A[j], H)], DP[h] + B[j])
    if DP[H] < ans:
        ans = DP[H]

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
h, n = map(int, input().split())
dp = np.zeros((n+1, h+1))
dp[0] = np.inf
for i in range(1, n+1):
    a, b = map(int, input().split())
    for j in range(1, h+1):
        if j >= a:
            dp[i][j] = min(
                dp[i-1][j], dp[i][j-a] + b,
            )
        else:
            dp[i][j] = min(
                dp[i-1][j], b
            )
print(int(dp[n][h]))

Submission status: Time Limit Exceeded

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

H,N=map(int,input().split())
L=[]
for i in range(N):
    T=[0,0,0]
    T[1],T[2]=map(int,input().split())
    T[0]=T[2]/T[1]
    L.append(T)
L=sorted(L)
n=1+H//L[0][1]
m=n*L[0][2]
L=sorted(L,key=lambda x: x[2],reverse=True)
def DP(MAX,minM,i,T,M):
    t=T
    m=M
    if(T>=MAX):
        return M
    if(m<minM):        
        tm=DP(MAX,minM,i,t+L[i][1],m+L[i][2])
        if(minM>tm):
            minM=tm
        if(len(L)-1 > i):
            tm=DP(MAX,minM,i+1,t,m)
            if(minM>tm):
                minM=tm
    return minM

tm=DP(H,m,0,0,0)

print(tm)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
H, N = map(int, input().split())
A_list = []
B_list = []
for i in range(N):
    A, B = map(int, input().split())
    A_list.append(A)
    B_list.append(B)

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

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

print(dp[-1])

Submission status: Time Limit Exceeded

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


def solve(H: int, N: int, A: "List[int]", B: "List[int]"):
    # AB = sorted(list(zip(A,B)),key=lambda x: -x[0]/x[1])

    # dp[i][j] i番目までの技からいくつか選んで体力H以下にするときの最小MP

    dp = [[10**9]*(H+10**4+1) for _ in range(N+1)]
    for i in range(N+1):
        dp[i][0] = 0

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

    answer = 10**9
    for i in range(H,H+10**4+1):
        answer = min(answer,dp[-1][i])
    print(answer)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    N = int(next(tokens))  # type: int
    A = [int()] * (N)  # type: "List[int]"
    B = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
    solve(H, N, A, B)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

### TESTCASE
test = ""
#test = \
"""
9 3
8 3
4 2
2 1
ans 4
"""

"""
5 2
4 4
2 3
ans 7
"""

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

"""
9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461
ans 139815
"""
############
test = list(reversed(test.strip().splitlines()))
if test:
    def input2():
        return test.pop()
else:
    def input2():
        return input()
####### MAIN
        
h, n = map(int, input2().split())    
ab = [tuple(map(int, input2().split())) for _ in range(n)]

dp = [0] * (h + 1)

for i in range(1, h+1):
    kouho = 10**15
    for c in ab:     
        kouho = min(kouho, dp[max(i-c[0], 0)] + c[1])
    
    dp[i] = kouho
    #print(i, kouho)
        
print(dp[-1])

Submission status: Time Limit Exceeded

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

ablist=[]
for i in range(N):
  a,b=map(int,input().split())
  ablist.append((a,b))
  
dp=[]
for i in range(N+1):
  dp.append([10**9]*(H+1))
  
for i in range(N+1):
  dp[i][0]=0
  
#print(dp)  
for i in range(1,N+1):
  ai,bi=ablist[i-1]
  for j in range(1,H+1):
    if j-ai<0:
      dp[i][j]=min(dp[i-1][j],bi)
    else:
      dp[i][j]=min(dp[i-1][j],dp[i][j-ai]+bi)
      
#print(dp)
print(dp[N][H])

Submission status: Time Limit Exceeded

Solution code:
from math import ceil, floor

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

if n == 1:
  print(ceil(h/l[0][0]) * l[0][1])
  exit(0)

dp = [ceil(hp/l[0][0]) * l[0][1] for hp in range(h + 1)]

for i in range(1, n):
  for hp in range(h + 1):
    if hp >= l[i][0]:
      dp[hp] = min([dp[hp], dp[hp - l[i][0]] + l[i][1]])
    else:
      dp[hp] = min([dp[hp], l[i][1]])

print(dp[-1])

Submission status: Time Limit Exceeded

Solution code:
#!python3

from heapq import heappush, heappop, heapify

iim = lambda: map(int, input().rstrip().split())

def resolve():
    H, N = iim()
    AB = [tuple(iim()) for i in range(N)]

    AB.sort(key=lambda a: (a[0]/a[1], a[0]), reverse=True)

    S = []
    for a, b in AB:
        n = H // a + 1
        h = H
        i = 1
        while n >= i:
            S.append((a*i, b*i))
            n -= i
            i <<= 1
        if n:
            S.append((a*n, b*n))

    N2 = len(S)
    def ubound(b, a, i):
        for j in range(i, N2):
            aj, bj = S[j]
            if a + aj >= H:
                return (b+bj, b + (H-a) * bj / aj)
            a += aj
            b += bj

        return (inf, inf)

    q = []
    u0, u1 = ubound(0, 0, 0)

    inf = float("inf")
    heappush(q, (u1, u0, 0, 0, 0))
    um = u0
    #print(AB)
    #print(H, S)
    while q:
        #print(q)
        uq0, uq1, aq, bq, i = heappop(q)

        if uq0 > um:
            break

        if i >= N2: continue

        ai, bi = S[i]
        if aq + ai < H:
            heappush(q, (uq0, uq1, aq + ai, bq + bi, i + 1))

        u0, u1 = ubound(bq, aq, i + 1)
        if u1 <= um:
            if u0 < um:
                um = u0
            if u1 <= um:
                heappush(q, (u1, u0, aq, bq, i + 1))

    print(um)



if __name__ == "__main__":
    resolve()

Submission status: Time Limit Exceeded

Solution code:
INF = 10**12
maxH = 2 * 10**4 + 10

def solve():
    H, N = map(int, input().split())
    ABs = [tuple(map(int, input().split())) for _ in range(N)]

    dp = [INF] * (maxH+1)
    dp[0] = 0
    for A, B in ABs:
        for h in range(maxH-A+1):
            h2 = h + A
            dp2 = dp[h] + B
            if dp2 < dp[h2]:
                dp[h2] = dp2

    print(min(dp[H:]))


solve()

Submission status: Time Limit Exceeded

Solution code:
h, n = map(int, input().split())
a = []
b = []
for i in range(n):
  a1, b1 = map(int, input().split())
  a.append(a1)
  b.append(b1)

mp = [10 ** 8] * (h + max(a))
mp[0] = 0
for i in range(h):
  for j in range(n):
    mp[i+a[j]] = min(mp[i+a[j]], mp[i] + b[j])

print(min(mp[h:]))