Countdown
Time limit1sMemory limit128 MB
Find the closest achievable value to a target by combining six given numbers with the four operations, keeping intermediate results positive integers.
- Level
Medium6 of 10
- Topics
- Brute force, Recursion, Combinatorics
- Solved
- No attempts yet
Problem
The TV show Countdown has a round where you obtain a number by combining six different numbers using the four basic operations: addition, subtraction, multiplication, and division. The basic rules are:
- The contestant selects six of twenty-four shuffled tiles. The tiles form two groups: four "large numbers" () and the rest "small numbers", which are two copies each of through . So the tile values come from .
- The contestant chooses how many large numbers are in the selection, anywhere from none.
- The contestant then has thirty seconds to get a number as close to the target as possible by combining the six selected numbers using addition, subtraction, multiplication, and division.
- Not all numbers need to be used.
- A number can be used as many times as it appears.
- Fractions are not allowed; only positive integers may appear at any stage of the calculation.
Given the six numbers and a target , determine how close to you can get.
Input
The first line contains the number of cases (). Each of the following lines contains six natural numbers from the set followed by a natural number (), the target.
Output
For each case, print on its own line a single integer: the smallest possible value of over all numbers obtainable from the six selected numbers under the rules above. Every selected number by itself counts as obtainable, so this value is always defined; it is exactly when the target itself can be reached.