LKS - Large Knapsack

The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items.

Just implement 0/1 Knapsack.

Input

First line contains two integers K and N, where K in the maximum knapsack size and N is the number of items. N lines follow where ith line describes ith item in the form vi and wi where vi is the value and wi is the weight of ith item.

Output

Output a single number - maximum value of knapsack. (All operations and the answer are guaranteed to fit in signed 32-bit integer.)

Time limit changed to 2s on 02.07.11.

Example

Input:
10 3
7 3
8 8
4 6

Output:
11

Constraints

K <= 2000000
N <= 500
Vi <= 10^7
Wi <= 10^7


Added by:Ace
Date:2013-06-24
Time limit:2s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64

hide comments
2017-05-18 09:31:17
I thought it need some complicated optimization, but it turns out not.
2017-05-01 19:45:43 shahzada
need some pretty good space optimisations.
2017-04-30 11:40:17
easy one!!!
2017-01-30 15:44:54
Mine complexity is N*K ( 10^9 )

Still wounder how it can be accepted here?
2016-12-30 17:38:57
silly mistake cost me 2 TLE
2016-12-13 09:54:38
knapsack + space optimization ,, got runtime error without space optimization .........
2016-11-01 09:57:36
plz explain output of the given input...i think it should be 14.
2016-07-08 13:13:12 Rudra
Segmentation fault while dynamic allocation of 2D array using malloc .any reason?
2016-06-29 13:26:00 bhavya singh
TLE in C
AC in C++
why ? :/
2016-05-28 14:07:53 sanjay
TOP DOWN DP WITH MEMORY OPTIMISATION. :)
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.