Problem
Calculator Language (CL) supports assignment, positive and negative integers and simple arithmetic. The allowable characters in a CL statement are thus:
All operators have the same precedence and are right associative, thus 15 - 8 - 3 = 15 - (8 - 3) = 10. As one would expect, brackets will force the expression within them to be evaluated first. Brackets may be nested arbitrarily deeply. An expression never has two operators next to each other (even if separated by a bracket), an assignment operator is always immediately preceded by a variable and the leftmost operator on a line is always an assignment. For readability, spaces may be freely inserted into an expression, except between a negative sign and a number. A negative sign will not appear before a variable. All variables are initialised to zero (0) and retain their values until changed explicitly.
Write a program that will accept and evaluate expressions written in this language. Each expression occupies one line and contains at least one assignment operator, and maybe more.
Input
Input will consist of a series of lines, each line containing a correct CL expression. No line will be longer than 100 characters. The file will be terminated by a line consisting of a single #.
Output
Output will consist of a series of lines, one for each line of the input. Each line will consist of a list of the final values of all variables whose value changes as a result of the evaluation of that expression. If more than one variable changes value, they should be listed in alphabetical order, separated by commas. If a variable changes value more than once in an expression, only the final value is output. A variable is said to change value if its value after the expression has been evaluated is different from its value before the expression was evaluated. If no variables change value, then print the message `No Change’. Follow the format shown below exactly.
Sample input
|
|
Sample output
|
|
Solution
題目描述:
給一個六則運算,並且所有運算由右往左,也就是題目提及的 right associative
,並且在每一個運算式之後輸出有改變值的變數結果。
題目解法:
要處理的問題相當多,按照一般的思路要做出 right associative
還不打緊,就像冪次的定義一樣,也就是把 stack 的嚴格遞增改成非嚴格遞增。
但是查閱討論區給定的數據後,如下所示
範例輸入
範例輸出
這表示著連括弧運算順序都是 right associative
,這一點相當苦惱,於是最後建造 tree,然後先拜訪右子樹、再拜訪左子樹來解決這些問題。
中間誤把 No Change
寫成 No change
,因此卡了不少 Wrong Answer
。
Sample Input:
AC Sample Output:
一開始還在想為什麼當 B = 4
時,B=B-6+B=100
會產出 B = -6
,由右往左運算。
- B = 100
- 6 + B = 106
- B - (6 + B) = 100 - 106 = -6
- B assign(=) -6
|
|