Segment Pricing

Interview

Time limit1sMemory limit128 MB

Summary
Choose a non-increasing fare for each boarding stop, with riders boarding only if their budget covers it, to maximize total revenue.
Level

Medium7 of 10

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

Problem

You run a subway line and want to set fares that maximize revenue, assuming you know exactly who will ride and each rider's budget.

The line has nn stops and therefore n−1n - 1 segments between consecutive stops. For simplicity, every rider is heading to the final stop nn, but riders board at different stops. You must choose a fare for each boarding stop ii (for 1≤i≤n−11 \le i \le n - 1).

For fairness, a stop farther from the destination may not be cheaper than one closer to it: the fare at stop ii must be at least the fare at stop i+1i + 1, since it covers a longer distance.

For each stop you are given the exact budget of every rider who wants to board there. A rider boards only if their budget is at least that stop's fare; otherwise they walk and pay nothing. No fare may exceed $5.00 (that is, 500500 cents), and every fare is between 00 and 500500 cents. The subway always has enough seats for everyone.

Maximize the total revenue, where the revenue collected at a stop is its fare multiplied by the number of riders who board there.

Input

The first line contains the number of data sets KK. Each data set has the following form:

  • The first line contains an integer nn (2≤n≤1002 \le n \le 100), the number of stops.
  • The next n−1n - 1 lines describe the boarding riders; line ii lists the riders boarding at stop ii (all of whom get off at stop nn). That line contains mim_i integers (0≤mi≤1000 \le m_i \le 100): the budgets bj≥0b_j \ge 0 (in cents) of those riders, given in non-decreasing order. An empty line means no rider boards at that stop.

A budget may exceed 500500; such a rider still boards at any fare up to the 500500-cent cap.

Output

For each data set, print Data Set x: on its own line, where xx is the data set's number (starting at 11), then print the maximum revenue in cents on the next line. Separate consecutive data sets with a single blank line.

Examples2

  1. Example 1

    Input
    1
    6
    110 111 112 113 114 150 150
    100 100 120 150
    500 700
    
    0 80 350
    
    Expected output
    Data Set 1:
    1530
    
  2. Example 2

    Input
    1
    2
    100 200 300
    
    Expected output
    Data Set 1:
    400