This page is still under construction.

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

Transportation

Time limit1sMemory limit128 MB

Summary
Choose a subset of passenger orders so that no route segment exceeds capacity n, maximizing total revenue.
Level

Medium5 of 10

Topics
Backtracking, Brute force
Solved
No attempts yet

Problem

An express train runs from station A to station B, stopping at several stations along the way. The stations are numbered in order: station A is number 00 and station B is number mm. The train can carry at most nn passengers, and on every segment of the route the total number of passengers on board must never exceed nn.

The price of a ticket equals the number of stops between the departure station and the destination station, counting the destination. In other words, a ticket from station SS to station TT costs T−ST - S.

Before the train leaves station A, reservation orders are collected from the intermediate stations. Each order is a triple (departure station SS, destination station TT, number of passengers PP), and the company must either accept an order in full or reject it in full. When the capacity does not allow every order to be accepted, carrying only some passengers of an order is not allowed.

If an order is accepted, its PP passengers travel from SS to TT and therefore occupy every segment in between. The revenue from one accepted order is (number of passengers) ×\times (ticket price) =P×(T−S)= P \times (T - S), and the total revenue is the sum over all accepted orders.

Write a program that, given the list of orders, determines the largest total revenue the company can earn.

Input

The input consists of several blocks. The first line of each block contains three integers nn, mm, and kk: the passenger capacity nn, the number mm of station B, and the number kk of orders. Each of the next kk lines describes one order as three integers SS, TT, PP: the departure station, the destination station, and the number of passengers.

A block contains at most 2222 orders, and the number mm of station B is at most 77. A block whose first line contains three zeros marks the end of the input and is not processed.

Output

For each block except the terminating one, print on its own line the largest total revenue that can be earned.

Examples1

  1. Example 1

    Input
    10 3 4
    0 2 1
    1 3 5
    1 2 7
    2 3 10
    10 5 4
    3 5 10
    2 4 9
    0 2 5
    2 5 8
    0 0 0
    
    Expected output
    19
    34