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 ≤ 107
Wi ≤ 107


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
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. :)
2016-03-29 20:30:22
its getting internal error in c++ 5.1 while the same code got AC in c++ 4.3.2!!!
2016-02-20 21:32:58
If you want to know how to do it in 0.0 time just look up best first branch and bound.
2016-02-18 11:49:53 minhthai
even O(k) space in java cannot get AC :(( any hint?
2016-02-03 18:32:06 Shubham Khandelwal
Was getting TLE but changing array type from long long to int, turned to AC. O(N*k) gets AC
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.