The Safe Secret
Time limit1sMemory limit256 MB
For each ring rotation, replace each ? with +, - or * and parenthesize to get the min and max values, then join their digits in order.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Intervals
- Solved
- No attempts yet
Problem
A nineteenth century duke built a room for his valuables and chose the code of its safe in an unusual way. He was so afraid of being robbed that he told nobody the code. He only wrote down how to obtain it, on a sheet of paper meant for his heir after his death. The paper read:
- Look at the inner side of the dukedom ring, which is now yours.
- Starting at the number closest to the ruby, copy the numbers and the symbols in clockwise order, leaving out the last symbol. That is the first sequence. Start at the next number and do the same, and you get the second sequence. Repeat until you have started at every number once.
- For each sequence, do the following.
- Replace every
?by+,-or*. Do that in all possible ways to get several arithmetic expressions. - Evaluate each expression. The sums, the differences and the products may be performed in any order. Do that in all possible orders to get several values.
- Take the minimum and the maximum of those values.
- Write the digits of the minimum and append to them the digits of the maximum. Do not write the sign. That is the code of the sequence.
- Replace every
- Concatenate the codes in the order the sequences were obtained. That string of digits is the safe secret.
The ring carries numbers and symbols engraved in a circle, in the order , , , , ..., , . The number closest to the ruby is . The -th sequence reads elements clockwise starting at , so it holds numbers and the symbols between them, and the last symbol is left out.
The symbol choices and the evaluation order are decided separately for each sequence, and each ? may take a different symbol. The operators keep their positions, and only the order of evaluation changes. For instance 1 - 5 + 0 * -2 - -3 gives 11 when it is evaluated as ((((1 - 5) + 0) * -2) - -3), and it gives -4 when it is evaluated as (1 - (5 + (0 * (-2 - -3)))).
If the minimum of a sequence is -4 and the maximum is 11, the code of that sequence is 411, because the sign of a negative value is dropped and only its digits are written.
Given the numbers and the symbols engraved on the ring, find the safe secret.
Input
The first line has one positive integer , the number of (number, symbol) pairs that form the ring.
The second line has elements , , , , ..., , , separated by single spaces. Each is a number and each is +, -, * or ?.
Output
Print the safe secret on a single line.
Constraints
- Every value produced by the process above fits in a signed 64 bit integer.