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
manas0008: 2016-02-02 17:33:20

Do only space optimisation but not time.First try WACHOVIA problem.

sudip_95: 2016-01-28 09:35:05

solved in 1.45s after optimizing. Can't understand how it can be solved in 0.00s. Can anyone explain how?

shantanu tripathi: 2016-01-11 16:44:25

lots of optimization needed from memory to time complexity.... nice :)

jefry33: 2015-12-12 07:42:33

Guys, can you help me? how to decrease memory for this problem? i using dynamic programming and it using large memory in Array...

hnvahidi: 2015-11-22 23:23:38

I got TLE , just changed array type from long long to int and got AC :-O
O(nk) solution passes

Roy Rohit: 2015-09-04 18:11:35

easy one!!!

Shalin Shah: 2015-07-09 20:53:52

I changed my 'for' loop to a 'while' loop and it got ACed. Can anybody specify a reason for that? It was giving a TLE with a 'for' loop.

Last edit: 2015-07-09 20:54:22
:.Mohib.:: 2015-06-14 15:51:33

Nice one :)

Saurabh Mishra: 2015-05-28 19:01:49

really .. a nice one ...thanks :)

shikhargarg: 2015-05-14 19:09:04

Just optimize the space... i got ac with complexity of n*k :)


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