给定一个前缀表达式,求其运算结果对 109+7 取模后的结果
保证该前缀表达式中每个运算数均为正整数且不超过 109,每个正整数前边均会有一个 # 表示该正整数从这里开始,该前缀表达式的运算符仅含有加号(+),减号(-),乘号(*)
该前缀表达式中的正整数不超过 2×105 个,字符串总长度不超过 3×106
输入一行,包含一个字符串,为一个前缀表达式
输出一行,包含一个非负整数,表示该前缀表达式运算结果对 109+7 取模后的结果
-*+#1#2#3#4
5
对于 30% 的数据,该前缀表达式中的正整数不超过 200 个,字符串总长度不超过 3×103
对于另外 20% 的数据,表达式中不含减号
对于另外 20% 的数据,表达式中不含乘号
对于 100% 的数据,该前缀表达式中的正整数不超过 2×105 个,字符串总长度不超过 3×106
#include <iostream>
#include <stack>
#include <algorithm>
#define mod 1000000007
using namespace std;
string s;
stack < long long > st;
long long x,a,b;
int main(){
cin >> s;
reverse(s.begin(),s.end());
for(int i = 0;i < s.size();i++){
if(s[i] == '#'){
st.push(x);
x = 0;
continue;
}
if(isdigit(s[i])){
x = (x << 3) + (x << 1) + (s[i] ^ 48);
x %= mod;
continue;
}
switch(s[i]){
case '+':a = st.top();st.pop();b = st.top();st.pop();st.push((a + b) % mod);break;
case '-':a = st.top();st.pop();b = st.top();st.pop();st.push((a - b) % mod);break;
case '*':a = st.top();st.pop();b = st.top();st.pop();st.push((a * b) % mod);break;
}
}
cout << st.top();
return 0;
}