I. 匪石不想计算(栈运算,大一期末考核)
题目来源:https://codeforces.com/gym/547381/problem/I
//
题意:给出+,-,^三种运算,包含括号,得出结果。
//
思路:“网上看的转为后缀表达式,然后栈模拟,没写出来,后面看的zzh的代码。”用两个栈来模拟,一个存数字,一个存运算符号。
1:如果碰到了数字,入num栈。
2:碰到),一直运算st栈中的运算符号,直到碰到(。
3:碰到运算符号,且栈顶运算符号优先级>=当前运算符号,进行运算。
//
题解:
点击查看代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int Mod=1e9+7;
stack<int>num;//存数字
stack<char>st;//存运算符号
int qmi(int a,int b){
int ans=1;
while(b){
if(b&1){ans=ans*a%Mod;}
a=a*a%Mod;
b>>=1;
}
return ans%Mod;
}
void dot(){
int num1=num.top();num.pop();
int num2=num.top();num.pop();
char op=st.top();st.pop();
if(op=='+'){num1=(num1+num2)%Mod;}
else if(op=='*'){num1=num1*num2%Mod;}
else if(op=='^'){num1=qmi(num2,num1)%Mod;}
num.push(num1);
return;
}
void solve(){
while(!num.empty()){num.pop();}
while(!st.empty()){st.pop();}//init
map<char,int>level;
level['+']=1,level['*']=2,level['^']=3;//运算优先级
string s;
cin>>s;
for(int i=0;i<s.length();i++){
auto &it=s[i];
if(isdigit(it)){//数字
int cnt=0;
while(i<s.length()&& isdigit(s[i])){
cnt=cnt*10+(s[i]-'0');
i++;
}
i--;
num.push(cnt);
}
else{//运算符号
if(it==')'){//一直匹配运算直到(
while (st.top() != '(') dot();
st.pop();
}
else{//其它符号,判断优先级
while(it!='(' && !st.empty() && st.top()!='(' && level[st.top()]>=level[it]){dot();}
st.push(it);//当前运算符入栈
}
}
}
while(!st.empty()){dot();}
cout<<num.top()<<endl;
return;
}
signed main()
{
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}