Buying Feed, II

Interview

Time limit1sMemory limit128 MB

Summary
Pick up to K pounds of feed from stores along a line, paying each store's price plus transport cost of distance carried, and minimize the total.
Level

Medium5 of 10

Topics
Greedy, Sorting, Math, Implementation
Solved
No attempts yet

Problem

Farmer John (FJ) needs to travel to town to buy KK pounds of feed (1≤K≤1001 \le K \le 100). Driving DD miles with KK pounds of feed in his truck costs D×KD \times K cents.

The county feed lot has NN stores (1≤N≤1001 \le N \le 100, conveniently numbered 11 through NN) that sell feed. Every store lies on a segment of the XX axis whose length is EE (1≤E≤3501 \le E \le 350). Store ii is at location XiX_i (0<Xi<E0 < X_i < E) on the number line and can sell up to FiF_i pounds (1≤Fi≤1001 \le F_i \le 100) of feed at a price of CiC_i cents (1≤Ci≤1,000,0001 \le C_i \le 1{,}000{,}000) per pound. Remarkably, a single point on the XX axis may host more than one store.

FJ starts at location 00 on the number line and can drive only in the positive direction, ultimately arriving at location EE carrying at least KK pounds of feed. Along the way he may stop at any store and buy any amount of feed up to that store's limit.

What is the minimum amount FJ must pay to buy and transport the KK pounds of feed? A solution is guaranteed to exist.

Input

  • Line 11: Three space-separated integers KK, EE, and NN.
  • Lines 22 to N+1N+1: Line i+1i+1 contains three space-separated integers XiX_i, FiF_i, and CiC_i describing store ii.

Output

  • Line 11: A single integer, the minimum cost for FJ to buy and transport the feed.

Examples3

  1. Example 1

    Input
    2 5 3
    3 1 2
    4 1 2
    1 1 1
    
    Expected output
    7
    
  2. Example 2

    Input
    5 10 2
    5 3 1
    1 10 1
    
    Expected output
    38
    
  3. Example 3

    Input
    1 10 2
    1 1 1
    9 1 5
    
    Expected output
    6