#P4544. [USACO10NOV] Buying Feed G

[USACO10NOV] Buying Feed G

Description

John drives to town and wants to bring back KK tons of feed. Transporting feed costs money: if his car currently carries XX tons, the cost per kilometer is X2X^2 yuan, so driving DD kilometers costs D×X2D\times X^2 yuan. John can buy feed from NN stores, all located on a number line. Store ii is at position XiX_i, sells feed at CiC_i yuan per ton, and has FiF_i tons in stock.

John starts at X=0X=0 and travels in the positive direction along the axis. His home is at X=EX=E. What is the minimum total cost for John to bring KK tons of feed home? Assume the sum of all stores’ stocks is at least KK.

For example, suppose there are three stores as shown below:

Coordinate X=1X=1 X=3X=3 X=4X=4 E=5E=5
Stock 11 11
Price 22

If K=2K=2, John’s optimal choice is to buy from the two stores closer to home. The money spent on the road is 1+4=51+4=5, the money spent at the stores is 2+2=42+2=4, for a total of 99 yuan.

Input Format

The first line contains three integers KK, EE, NN.

Lines 22 to N+1N+1: line i+1i+1 contains three integers XiX_i, FiF_i, CiC_i.

Output Format

Output a single integer, the minimum total cost.

2 5 3
3 1 2
4 1 2
1 1 1
9

Hint

Constraints

1K100001 \leq K \leq 10000, 1E5001 \leq E \leq 500, 1N5001 \leq N \leq 500.

0<Xi<E0 < X_i < E, 1Fi100001 \leq F_i \leq 10000, 1Ci1071 \leq C_i \leq 10^7.

Translated by ChatGPT 5