Card Operation (Large)
Time limit5sMemory limit512 MB
Order a set of arithmetic cards applied to a starting value to maximize the final rational result, printed as a reduced fraction.
- Level
Hard8 of 10
- Topics
- Greedy, Sorting, Math, Brute force
- Solved
- No attempts yet
Problem
A card game called Operation is played with a deck of operation cards. Each card holds one arithmetic operation (addition, subtraction, multiplication, or division) and one integer right operand for that operation. A card can read + 0, or - -2, or / -4. Operands can be negative or zero, but a division card never has 0 as its operand.
In each round a starting integer is chosen and a set of cards is laid out. The player picks an order for the cards and uses each card exactly once. The operations are then applied to in that order, and a final result comes out.
The operands are integers, but the operations run on rational numbers. Suppose the starting value is 5 and the cards are + 1, - 2, * 3, and / -2. In that order the final result is . The cards apply in the chosen order and operator precedence is ignored. With the order - 2, / -2, + 1, * 3 the result is , which is the largest value this set of cards can reach.
Given the starting value and the cards, find the maximum possible final value. Report it as an irreducible fraction with a positive denominator.
Input
The first line holds the number of test cases . Each test case starts with one line holding two integers and , the starting value and the number of cards. Then lines follow. The i-th of those lines describes one card and holds one character , which is +, -, *, or /, and one integer .
Limits
- is one of
+,-,*,/, for all i. - , for all i.
- If is
/, then , for all i.
Output
For each test case, print one line holding Case #x: y z, where is the test case number starting from 1, and and are integers such that is the maximum possible final value, and have no common divisor other than 1 and -1, and is strictly greater than 0.
Notes
The numerator can run far past the range of a 64-bit integer, so the answer needs arbitrary precision arithmetic.
Zero has exactly one valid form here, 0 1. The form 0 2 is invalid because it reduces, and 0 -1 is invalid because the denominator must be positive.