1356:计算(calc)
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 7184 通过数: 2863
【题目描述】
小明在你的帮助下,破密了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是密码。小明数学学得不好,还需你帮他的忙。(“/”用整数除法)
【输入】
共1行,为一个算式。
【输出】
共1行,就是密码。
【输入样例】
1+(3+2)*(7^2+6*9)/(2)
【输出样例】
258
分析:
这道题和栈是跑不了关系,当然也可以用配合表达式来组合使用。使用STL的stack的确很省事。后续还会更新使用表达式树的解法
栈解法代码如下:
#include<stack>
#include<cstdio>
#include<cstring>
#include<cmath>
std::stack <int>num;
std::stack <char>expr;
char s[32768];
int check(char c){ //运算顺序
if(c=='-' || c=='+')return 1;
else if(c=='*'|| c=='/')return 2;
else if(c=='^')return 3;
else return 0;
}
void deal(){
int a=num.top();
num.pop();
int b=num.top();
num.pop();
char c=expr.top();
expr.pop();
if(c=='+')num.push(a+b);
else if(c=='-')num.push(b-a);
else if(c=='/')num.push(b/a);
else if(c=='*')num.push(a*b);
else if(c=='^')num.push(pow(b,a));
}
int main(){ //前提是保证数据合法
int temp=0;
bool digtal=false;
scanf("%s",s+1);
int n=strlen(s+1);
for(int i=1;i<=n;i++){
if(s[i]>='0' && s[i]<='9'){
temp=s[i]-'0'+temp*10;
digtal=true;
}
else{
if(digtal){
num.push(temp);
temp=0;
digtal=false;
}
if(s[i]=='('){
expr.push(s[i]);
continue;
}
else if(s[i]==')'){
while(expr.top()!='(')
deal();
expr.pop();
continue;
}
while(!expr.empty() &&check(expr.top())>=check(s[i])) //能提前运算
deal();
expr.push(s[i]);
}
}
if(digtal) //漏一个
num.push(temp);
while(!expr.empty())
deal();
printf("%d",num.top());
return 0;
}
程序运行结果:
通过
测试点 | 结果 | 内存 | 时间 |
测试点1 | 答案正确 | 428KB | 5MS |
测试点2 | 答案正确 | 424KB | 4MS |
测试点3 | 答案正确 | 424KB | 3MS |
测试点4 | 答案正确 | 424KB | 6MS |
测试点5 | 答案正确 | 436KB | 5MS |
挺快的!,加油,CSP-S 2021