Buying Feed

Time limit2sMemory limit128 MB

Summary
Buy at least K pounds of feed from stores along a 1D route, paying purchase cost plus K^2 cents per mile for the load carried, and minimize the total.
Level

Hard8 of 10

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

Problem

Farmer John (FJ) must travel to town to pick up KK (1≤K≤10 0001 \le K \le 10\,000) pounds of feed. Driving 11 mile while carrying KK pounds of feed costs K×KK \times K cents; driving DD miles with the same load costs D×K×KD \times K \times K cents.

FJ can buy feed from any of NN (1≤N≤5001 \le N \le 500) stores, numbered 1…N1 \ldots N. All stores sit on a segment of the X axis of length EE (1≤E≤5001 \le E \le 500) miles. Store ii is at location XiX_i (0<Xi<E0 < X_i < E) and sells feed at CiC_i (1≤Ci≤10 000 0001 \le C_i \le 10\,000\,000) cents per pound, up to FiF_i (1≤Fi≤10 0001 \le F_i \le 10\,000) pounds. More than one store may share the same location.

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

What is the minimum total amount FJ must pay to buy and transport KK pounds of feed? It is guaranteed that the stores together can supply enough feed.

For example, suppose FJ needs 22 pounds and there is one store at each of the locations 11, 33, and 44 on a number line spanning 0…50 \ldots 5:

      0   1   2   3   4   5   X
      +---|---+---|---|---+
          1       1   1
          1       2   2

Under each store, the first row of numbers is how many pounds it can sell and the second row is its price in cents per pound. So the store at location 11 sells 11 pound for 11 cent, and the stores at locations 33 and 44 each sell 11 pound for 22 cents.

The cheapest plan is to buy 11 pound from the store at location 33 and 11 pound from the store at location 44. The feed costs 2+2=42 + 2 = 4 cents. Driving from 00 to 33 costs nothing because FJ carries no feed. Driving from 33 to 44 moves 11 pound over 11 mile, costing 1×1×1=11 \times 1 \times 1 = 1 cent; driving from 44 to 55 moves 22 pounds over 11 mile, costing 1×2×2=41 \times 2 \times 2 = 4 cents. The total is 4+1+4=94 + 1 + 4 = 9 cents.

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.

Output

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

Examples1

  1. Example 1

    Input
    2 5 3
    3 1 2
    4 1 2
    1 1 1
    
    Expected output
    9