Cash Machine

Interview

Time limit1sMemory limit128 MB

Summary
Given a cash target and limited counts of several bill denominations, find the maximum total not exceeding the target using a bounded-knapsack style search.
Level

Medium4 of 10

Topics
Dynamic programming, Brute force
Solved
No attempts yet

Problem

A bank plans to install a cash-withdrawal machine. For a requested amount, the machine delivers bills from its supply. It uses exactly NN distinct denominations D1,D2,…,DND_1, D_2, \dots, D_N, and for each denomination DkD_k it holds a supply of nkn_k bills.

For example, N=3N = 3 with (n1,D1)=(10,100)(n_1, D_1) = (10, 100), (n2,D2)=(4,50)(n_2, D_2) = (4, 50), (n3,D3)=(5,10)(n_3, D_3) = (5, 10) means the machine holds 10 bills of denomination 100, 4 bills of denomination 50, and 5 bills of denomination 10.

Let cash\mathit{cash} be the requested amount. Write a program that computes the maximum amount not exceeding cash\mathit{cash} that the machine can deliver using its available bills.

Input

The input contains several data sets and is read until end-of-file. Each data set describes one transaction in the form

cash N n1 D1 n2 D2 ... nN DN

where 0≤cash≤1000000 \le \mathit{cash} \le 100000 is the requested amount, 0≤N≤100 \le N \le 10 is the number of denominations, 0≤nk≤10000 \le n_k \le 1000 is the number of available bills of denomination DkD_k, and 1≤Dk≤10001 \le D_k \le 1000 for k=1,…,Nk = 1, \dots, N. Whitespace may appear freely between the numbers. The input is always well-formed.

Output

For each data set, print on its own line the maximum amount of cash, not exceeding the requested amount, that the machine can deliver.

Notes

If the requested amount cannot be formed exactly, deliver the largest amount that does not exceed it. If the machine has no bills to offer (for example N=0N = 0) or the requested amount is 00, the delivered amount is 00. Several different bill combinations may add up to the same delivered amount.

Examples1

  1. Example 1

    Input
    735 3  4 125  6 5  3 350
    633 4  500 30  6 100  1 5  0 1
    735 0
    0 3  10 100  10 50  10 10
    
    Expected output
    735
    630
    0
    0