Operation (Small)
Time limit5sMemory limit512 MB
Given a start value S and up to 15 operation cards, order all cards to maximize the final rational result, printed as an irreducible fraction with positive denominator.
- Level
Hard8 of 10
- Topics
- Brute force, Backtracking, Math, Implementation
- Solved
- No attempts yet
Problem
A card game called Operation is played with cards. Each card holds one arithmetic operation (addition, subtraction, multiplication, or division) and one integer , the right operand of that operation. A card can read + 0, - -2, or / -4. An operand can be negative or zero, but a division card never has 0 as its operand.
In one round you get a starting integer and a set of cards. You choose an order for the cards and use each card exactly once. The operations are applied to in that order, and the last value is the result of the round.
Every operand on a card is an integer, but the operations run on rational numbers. Suppose the starting value is 5 and the cards are + 1, - 2, * 3, / -2. Used in that order the result is . Operator precedence does not apply, the cards are applied in the order you choose. Used in the order - 2, / -2, + 1, * 3 the result is , which is the largest value this set of cards can reach.
Given a set of cards, find the largest final value. Write it as an irreducible fraction with a positive denominator.
Input
The first line has the number of test cases . Each test case begins with a line holding two integers and , the starting value and the number of cards. The next lines describe the cards. The -th of those lines has one character for the operation and one integer for the operand.
Limits
- is one of
+,-,*,/for all . - for all .
- If is
/, then .
Output
For each test case, print one line Case #x: y z, where is the test case number starting from 1, and and are integers such that is the largest final value of the game, and have no common divisor other than 1 and -1, and is strictly greater than 0.
Notes
In the first sample case, playing * 2 before - 3 gives -1, and the required form of that value is -1 1.
The second sample case is the one described in the statement.
In the third sample case the order of the cards does not change the result. The numerator of the answer does not fit in a 64-bit integer.
In the fourth sample case the largest result is 1, reached for example by / -1, * 0, - -1.
In the fifth sample case 0 1 is the only valid answer. 0 2 can be reduced, and 0 -1 has a denominator that is not positive.