火星文计算
标题:火星文计算 | 时间限制:1秒 | 内存限制:262144K | 语言限制:不限
已知火星人使用的运算符为#、$,其与地球人的等价公式如下:
x#y = 2*x+3*y+4
x$y = 3*x+y+2
1、其中x、y是无符号整数
2、地球人公式按C语言规则计算
3、火星人公式中,$的优先级高于#,相同的运算符,按从左到右的顺序计算
现有一段火星人的字符串报文,请你来翻译并计算结果。
x#y = 2*x+3*y+4
x$y = 3*x+y+2
1、其中x、y是无符号整数
2、地球人公式按C语言规则计算
3、火星人公式中,$的优先级高于#,相同的运算符,按从左到右的顺序计算
现有一段火星人的字符串报文,请你来翻译并计算结果。
#include <vector> #include <iostream> #include <stack> #include <string> #include <unordered_map> using namespace std; #define TOP() stoull(_stack.top()); _stack.pop() #define RULE1(x, y) 3 * x + y + 2 #define RULE2(x, y) 2 * x + 3 * y + 4 unordered_map<string, int> level = { { "$", 10 }, { "#", 5 }, }; string calc(vector<string> &arr) { stack<string> _stack; for (const string &i : arr) { if (level.find(i) != level.end()) { uint64_t n1 = TOP(); uint64_t n0 = TOP(); if (i == "$") { _stack.push(to_string(RULE1(n0, n1))); } else { _stack.push(to_string(RULE2(n0, n1))); } } else { _stack.push(i); } } if (!_stack.empty()) { return _stack.top(); } return string(); } string getNumber(const string &str, size_t &index) { string number; for (; index < str.size(); ++index) { if (isdigit(str[index])) { number += str[index]; } else { --index; break; } } return number; } void save(vector<string> &arr, stack<string> &_stack, const string &val) { int l0 = level[val]; while (!_stack.empty()) { int l1 = level[_stack.top()]; if (l0 > l1) { break; } else { arr.push_back(_stack.top()); _stack.pop(); } } _stack.push(val); } vector<string> getExpr(const string &str) { vector<string> expr; stack<string> symbol; for (size_t i = 0; i < str.size(); ++i) { if (!isdigit(str[i])) { save(expr, symbol, string(1, str[i])); } else { expr.push_back(getNumber(str, i)); } } while (!symbol.empty()) { expr.push_back(symbol.top()); symbol.pop(); } return expr; } int main() { string str; cin >> str; vector<string> arr = getExpr(str); cout << calc(arr) << endl; return 0; }
while True: try: input_ls = input().split("#") res = input_ls[0] if "$" in res: ret = res.split("$") res = ret[0] for num in ret[1:]: res = 3 * int(res) + int(num) + 2 else: res = int(res) for i in range(1, len(input_ls)): if "$" in input_ls[i]: num_list = input_ls[i].split("$") temp = num_list[0] for num in num_list[1:]: temp = 3 * int(temp) + int(num) + 2 res = 2 * int(res) + 3 * int(temp) + 4 else: res = 2 * int(res) + 3 * int(input_ls[i]) + 4 print(res) except: break