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


hide comments
Nandan Mankad: 2014-11-04 08:28:02

Can anyone help me with TLE in Java. I think I am using proper optimized DP. Not sure it gets TLE. :(

deep prakash: 2014-10-08 18:58:30

can plz smone comment here how to solve knapsack problems with these large constraints i cnt find any help on internet,,

Rishi: 2014-10-01 08:04:40

will O(nk) time complexity pass???

bony2023: 2014-08-30 20:31:56

Top down -> WA
Bottom up -> AC :D
Anyways nice one.

Pratyush Kar: 2014-06-29 10:56:11

yes! 0.00 in C++

ayush: 2014-06-27 18:45:21

Learnt something new

surayans tiwari(http://bit.ly/1EPzcpv): 2014-06-20 12:24:15

heyy i am again again getting wrong ans i tried every possible test case seriously i need help
<snip>

Last edit: 2022-09-27 20:32:14
heatOn: 2014-05-25 04:51:50

vectors are slow. Using vector gave TLE !!
Use normal array for knapsack instead of vectors .

mohit gupta: 2014-04-05 21:24:48

dont know y
bt my solution got acepted yet its giving wrong result in the test case provided here

californiagurl: 2014-03-16 08:12:01

a senior at my colg taught me this optimization,, which is why i'm probably not as excited about getting this right ....i've always solved DP problems with this optimization


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