Guess the Numbers
InterviewTime limit1sMemory limit128 MB
Determine whether some permutation of up to 5 given values assigned to the unknowns in a fully parenthesized arithmetic expression makes it evaluate to a target result.
- Level
Medium4 of 10
- Topics
- Brute force, Recursion, String
- Solved
- No attempts yet
Problem
John has never been very good at maths. Because of his poor grades, his parents have enrolled him at the Academic Coalition of Mathematics (ACM). Despite how much his parents are paying for the ACM, John does not pay much attention in class. Today, however, he began to think about all the effort his parents are putting into his education, and he started to feel somewhat... guilty. So he has made a decision: he is going to improve his maths grades!
No sooner had he resolved to pay attention than the lesson ended. The only thing he managed to do was to hurriedly copy what was on the blackboard into his notebook. Today the teacher was explaining basic arithmetic expressions with unknowns. He vaguely remembers that his classmates were substituting values into the unknowns to obtain the expressions' results. In all the rush, though, John wrote down the expressions, the values, and the results in a jumble, so he no longer knows which value goes with each unknown, or which result goes with each expression.
That is why he needs your help. Given an expression, a set of values, and a result, he wants to know whether it is possible to assign those values to the unknowns so that the expression evaluates to the given result. The particular assignment does not matter to John, since he wants to work it out himself. He only wants to know whether it is possible.
Input
Each test case consists of two lines:
- The first line contains a sequence of natural numbers. The first, (), is the number of unknowns that occur in the expression. It is followed by integers (), the values to be assigned to the unknowns. Finally, an integer () gives the desired result of evaluating the expression.
- The second line contains an arithmetic expression made up of lowercase letters (
a-z), parentheses ((and)), and the binary operators+,-, and*. The expression contains the unknowns, represented by distinct lowercase letters with no repetitions. It contains no blanks and is always syntactically correct: it is either a single unknown, or has the form(e1 op e2), wheree1ande2are expressions andopis one of the three binary operators.
The input ends with a dummy test case consisting of a single line containing 0 0, which must not be processed.
Output
For each test case, print a single line containing YES if there is an assignment of the values to the unknowns that makes the expression evaluate to , and NO otherwise. Each value must be assigned to exactly one unknown.