Nasty Calculations
Time limit1sMemory limit128 MB
Evaluate a postfix arithmetic formula modulo B for up to 100000 given base-B values of x and print only the last digit each time.
- Level
Medium5 of 10
- Topics
- Stack, Math, Implementation
- Solved
- No attempts yet
Problem
You are given a formula of a single variable , together with many values of . For each value you must evaluate and report only its last digit.
Because can be very large, its exact value is not needed — only its last digit. Every number in this task (the formula, each value of , and every answer) is written in the base- positional numeral system for a given integer .
Postfix notation
The formula is given in postfix notation, also known as Reverse Polish Notation (RPN). In ordinary infix notation an operator is written between its operands, e.g. 1 + 2, 1 + 2 * 3, or (1 + 2) * 3. In postfix notation the operator is written directly after its operands, so the same expressions become 1 2 +, 1 2 3 * +, and 1 2 + 3 *. RPN needs no parentheses, because the order of the operands and operators already determines the expression uniquely.
Base- numeral systems
In the base- system a digit string represents , where every digit satisfies . Digits greater than 9 are written with uppercase letters: A = 10, B = 11, ..., Z = 35. For example, 29 in base 10 is written 45 in base 6 and 1D in base 16.
Input
The first line contains two integers and separated by a single space, where is the base of the numeral system and is the number of values of .
The second line describes the formula in postfix notation as a sequence of elements separated by single spaces. Each element is one of:
- A string of digits and uppercase letters, denoting a non-negative integer written in base (its value does not exceed 2000000000).
- The lowercase letter
x, standing for the variable. +(addition),-(subtraction), or*(multiplication).
Each of the next lines contains one value of , written in base in the same way (its value does not exceed 2000000000).
The input is guaranteed to be valid: the second line is a well-formed postfix expression, and every string of digits and uppercase letters is a valid integer in base . The second line contains at most 100000 characters.
Output
Print exactly lines. The -th line must contain a single character — a digit or an uppercase letter — equal to the last digit, in base , of for the value of on the -th line of the input. It is guaranteed that is non-negative for every given value of .