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
2015-01-27 16:16:09 breaking_code
o(n*m) will never pass... do optimization....starts iterating j from
j = sack_capacity - wt[i] to 0.... :)
2015-01-07 16:31:52 .::Austin::.
Fine on ideone, runtime error over here :(
2014-12-31 19:56:28 ALISHA
its new year's eve fellas which begins with the green band..huhuhu.
Never thought that fast io could get my solution ac.Try it guys in case you are getting TLE.;)

keep your constraints to minimum level guys.
my code for O(n)(k) time got TLE,while O(n-1)(k) got AC.

Last edit: 2014-12-31 20:01:52
2014-12-19 08:31:26 kancha
done :D

Last edit: 2014-12-19 11:43:21
2014-11-04 08:28:02 Nandan Mankad
Can anyone help me with TLE in Java. I think I am using proper optimized DP. Not sure it gets TLE. :(
2014-10-08 18:58:30 deep prakash
can plz smone comment here how to solve knapsack problems with these large constraints i cnt find any help on internet,,
2014-10-01 08:04:40 Rishi
will O(nk) time complexity pass???
2014-08-30 20:31:56 bony2023
Top down -> WA
Bottom up -> AC :D
Anyways nice one.
2014-06-29 10:56:11 Pratyush Kar
yes! 0.00 in C++
2014-06-27 18:45:21 ayush
Learnt something new
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.