Exact Measurement

Time limit1sMemory limit128 MB

Summary
Each box offers up to q_i masses of weight 10^k_i; find the fewest boxes to open so the chosen masses sum to exactly x.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, Math, Bit manipulation
Solved
No attempts yet

Problem

Peter works in a chemistry laboratory. For a new experiment he must measure out exactly xx nanograms (ng) of a reagent. He has a balance and a collection of standard masses.

The masses are stored in nn sealed boxes. Box ii holds qiq_i identical masses, each weighing 10ki10^{k_i} ng. To take masses out of a box he must open it, and from an opened box he may take any number of its masses, from 00 up to qiq_i.

Peter wants the total weight of the masses he takes to be exactly xx ng while opening as few boxes as possible. Determine the minimum number of boxes he must open.

Input

The first line contains two integers xx and nn (1≤x≤10181 \le x \le 10^{18}, 1≤n≤1051 \le n \le 10^5).

Each of the next nn lines contains two integers kik_i and qiq_i describing one box (0≤ki≤180 \le k_i \le 18, 1≤qi⋅10ki≤10181 \le q_i \cdot 10^{k_i} \le 10^{18}).

Output

Print a single integer: the minimum number of boxes Peter must open to measure exactly xx ng. If it is impossible to measure exactly xx ng, print −1-1.

Examples3

  1. Example 1

    Input
    289 4
    2 3
    1 5
    1 8
    0 30
    
    Expected output
    3
    
  2. Example 2

    Input
    300 4
    2 3
    1 5
    1 7
    0 30
    
    Expected output
    1
    
  3. Example 3

    Input
    201 1
    2 3
    
    Expected output
    -1