Work Reduction

Interview

Time limit1sMemory limit128 MB

Summary
For each agency with per-unit cost A and halving cost B, find the minimum cost to cut N units of paperwork down to exactly M.
Level

Medium6 of 10

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

Problem

Paperwork is piling up on your desk, and tension at work is rising. Your boss has threatened to fire you unless you make progress by the end of the day. Right now you have NN units of paperwork on your desk, and your boss demands that exactly MM units remain by the end of the day.

Your only hope is to hire help. Several agencies offer paperwork-reduction plans, and each agency offers the following two operations:

  • For $A they reduce your paperwork by one unit.
  • For $B they reduce your entire paperwork by half (rounding down when the amount is odd).

Paperwork can never be reduced below 0.

Your task is to print, for each agency, its name together with the minimum cost of using that agency to reach your target, as a sorted table.

Input

The first line of input contains a single positive integer, the number of test cases that follow. Each test case begins with three space-separated positive integers NN, MM, and LL: NN is your starting workload, MM is your target workload, and LL is the number of available agencies (1≤M≤N≤1000001 \le M \le N \le 100000, 1≤L≤1001 \le L \le 100). The next LL lines each have the form NAME:A,B, where AA and BB are that agency's rates as described above (0≤A,B≤100000 \le A, B \le 10000). Each agency name has length between 1 and 16 and consists only of capital letters, and all agency names are unique.

Output

For each test case, first print Case X on its own line, where XX is the case number. Then print the table of agency names and their minimum costs, sorted in non-decreasing order of minimum cost. Break ties among agencies with equal minimum cost alphabetically by agency name. On each line of the table, print the agency name, a single space, and the minimum cost for that agency to reach the target.

Examples1

  1. Example 1

    Input
    2
    100 5 3
    A:1,10
    B:2,5
    C:3,1
    1123 1122 5
    B:50,300
    A:1,1000
    C:10,10
    D:1,50
    E:0,0
    
    Expected output
    Case 1
    C 7
    B 22
    A 37
    Case 2
    E 0
    A 1
    D 1
    C 10
    B 50