King Thrór's Gold
Time limit1sMemory limit128 MB
Count the ways to choose exactly k distinct bar values summing to T, and list all solutions in lexicographic order when there are at most 20.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Backtracking, Sorting, Combinatorics
- Solved
- No attempts yet
Problem
Dwarf king Thrór wants to reward his best warriors with some of his gold bars. The dwarves' unit of currency is the Mirian. Thrór owns bars of distinct values Mirians. He wants to hand out exactly bars whose values add up to a target total of Mirians. Because his warriors are not equally deserving, they will in general receive bars of different values.
Thrór asks his brother Frór to work out in how many different ways the target can be written as a sum of the values of exactly distinct bars.
For example, with the bars , handing out bars for a target of has four solutions:
, , , .
For the same target with warriors there are only two:
, .
Write a program that, given the target , the number of warriors , and the bar values , reports how many different ways can be formed as the sum of exactly distinct values from . Whenever the number of solutions is 20 or fewer, the program must also list every solution in lexicographically increasing order: solutions using the smallest bar come first; among those, solutions using the next smallest bar come first; and so on. Within each solution the values are printed in increasing order.
Input
The first line contains the number of test cases (). Each test case has the following format:
- A line with the target value and the number of warriors , separated by a space (, ).
- A line with the number of gold bars ().
- The values of the bars. They are distinct positive integers listed in strictly increasing order. (They may span more than one line.)
The number of solutions is guaranteed to fit in a signed 64-bit integer (it is less than ).
Output
For each test case, in the order given, print the following block:
Test case X
Target sum = T
Number of warriors = k
V = {v1, v2, ..., vn}
Number of solutions = C
Here X is the 1-based test-case number; T, k, and the values are echoed from the input (the values inside the braces are separated by a comma and a space); and C is the number of ways to form the target. The Target sum, Number of warriors, and V = {...} lines each begin with a single leading space; the Number of solutions line does not.
If C is 20 or fewer, print one additional line for each solution, in lexicographically increasing order. Each such line begins with a single leading space followed by the chosen values in increasing order, separated by single spaces.
Print one blank line between consecutive test cases.