This page is still under construction.

Parts of this page are still being built. What you see may change.

Buying Notebooks

Interview

Time limit1sMemory limit128 MB

Summary
Each store has a fixed shipping fee, a per-notebook price, and limited stock; buy exactly N notebooks across stores at minimum total cost.
Level

Medium6 of 10

Topics
Dynamic programming, Sorting, Greedy, Array
Solved
No attempts yet

Problem

Minhyuk wants to buy NN notebooks. He has already surveyed the notebook prices at MM online stores.

Store ii sells one notebook for pip_i won and has sis_i notebooks in stock. Placing an order with a store incurs a shipping fee of oio_i won, charged only once no matter how many notebooks you buy. You may not order more than the sis_i notebooks a store has in stock.

Write a program that computes the minimum cost of buying NN notebooks.

Input

The first line contains the number of test cases TT (T≤100T \le 100). Each test case has the following format.

  • The first line contains the number of notebooks to buy NN and the number of stores MM (1≤N≤10,0001 \le N \le 10{,}000, 1≤M≤1001 \le M \le 100, N≤∑siN \le \sum s_i).
  • Each of the next MM lines contains a store's stock sis_i, price pip_i, and shipping fee oio_i (0≤si,pi≤10,0000 \le s_i, p_i \le 10{,}000, 0≤oi≤1,000,0000 \le o_i \le 1{,}000{,}000).

Output

For each test case, print the minimum cost of buying NN notebooks on its own line.

Examples2

  1. Example 1

    Input
    2
    20 4
    5 5 6
    10 4 12
    15 6 9
    20 7 0
    10 2
    5 0 50
    1000 10 0
    
    Expected output
    118
    100
    
  2. Example 2

    Input
    1
    1 1
    1 5 3
    
    Expected output
    8