题目描述
小科在你的帮助下,破解了第一道密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是密码。小科数学学得不好,还需你帮他的忙。(“/”用整数除法)
输入格式
共1行,为一个算式。
输出格式
共1行,就是密码。
输入输出样例
输入样例1:
1+(3+2)*(7^2+6*9)/(2)
输出样例1:
258
【耗时限制】1000ms 【内存限制】128MB
//
//Created by Carlgood.
//
//Note:This program is written in version DEV-C++ 5.11.
# include<iostream>
# include<cmath>
# include<string>
# include<cstring>
# include<cstdio>
# include<algorithm>
# include<sstream>
# include<iomanip>
# include<vector>
# include<queue>
# include<deque>
# include<stack>
# include<stdio.h>
# define This_program_is_written_by_Carlgood_Programming_Studio 9876543210
using namespace std;
stack<long long> nds;//操作数栈
stack<char> tor;//操作符栈
int level(char ch)//操作符优先级
{
if(ch=='+'||ch=='-') return 1;
else if(ch=='*'||ch=='/') return 2;
else if(ch=='^') return 3;
return 0;//左括号 优先级最低
}
void Scratch()
{
char ch;
long long op1,op2,op;
ch=tor.top();tor.pop();//取操作符
op2=nds.top();nds.pop();
op1=nds.top();nds.pop();
if(ch=='+') op=op1+op2;
if(ch=='-') op=op1-op2;
if(ch=='*') op=op1*op2;
if(ch=='/') op=op1/op2;
if(ch=='^') op=pow(op1,op2);
nds.push(op);
}
int main()
{
char ch;
int num=0;
bool flag=false;
while(cin>>ch)
{
//1.对操作数的处理
if(ch>='0'&&ch<='9')
{
num=num*10+ch-'0';
flag=true;//等待入栈
continue;
}
if(flag)//非数字字符,判断数字是否需要入栈
{
nds.push(num);
num=0;
flag=false;
}
//2.对操作符的处理
if(ch=='(') tor.push(ch);//左括号直接入栈
else if(ch==')')
{
while(!tor.empty()&&tor.top()!='(')
{
Scratch();
}
tor.pop();
}//将右括号到左括号的全部数都计算完
else if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='^')
{
while(!tor.empty()&&level(tor.top())>=level(ch)) Scratch();//栈顶运算符的优先级>=当前运算符的优先级
tor.push(ch);//当前操作符入栈
}
}
if(flag) nds.push(num);//最后一个数字需要入栈
while(!tor.empty()) Scratch();
cout<<nds.top();
return 0;
}