【題目描述】小明在你的幫助下,破密了Ferrari設的密碼門,正要往前走,突然又出現了一個密碼門,門上有一個算式,其中只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,求出的值就是密碼。小明數學學得不好,還需你幫他的忙。(“/”用整數除法) 【輸入】共1行,爲一個算式。 【輸出】共1行,就是密碼。 【輸入樣例】1+(3+2)*(7^2+6*9)/(2) 【輸出樣例】258 |
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
#include <set>
#include <queue>
#include <stack>
#define sf(a) scanf("%d\n",&a)
#define pf(a) printf("%.2lf\n",a)
#define pi acos(-1.0)
#define E 1e-8
#define ms(a) memset(a,0,sizeof a)
#define rep(a,b,c) for(int a=b;a<=c;a++)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int idata=1e6+5;
int i,j,k;
int judge,flag,temp;
int n,m,t,ans;
int maxx=0,minn=inf;
int cnt,len,sum;
//int dp[idata][idata];
priority_queue<ll, vector<ll>,less<ll> >q;
stack<int>s;
stack<char>sc;
char ch[idata];
int level(char c)
{
switch(c)
{
case '+':return 1;
case '-':return 1;
case '*':return 2;
case '/':return 2;
case '^':return 3;
default : return 0;
}
}
void calc()
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
char c=sc.top();
sc.pop();
switch(c)
{
case '+':s.push(a+b);break;
case '-':s.push(b-a);break;
case '*':s.push(a*b);break;
case '/':s.push(b/a);break;
case '^':s.push(pow(b,a));break;
}
//return;
}
int main()
{
cin>>ch;
len=strlen(ch);
/*ch[0]='(';
ch[len]=')';*/
for(i=0;i<len;i++)
{
if(ch[i]>='0'&&ch[i]<='9')
{
temp=temp*10+(ch[i]-'0');
flag=1;
}
else
{
if(flag)
{
s.push(temp);
temp=0;
flag=0;
}
if(ch[i]=='(')
{
sc.push('(');
continue;
}
if(ch[i]==')')
{
while(sc.top()!='(')
{
calc();
}
sc.pop();
continue;
}
while(!sc.empty()&&level(sc.top())>=level(ch[i]))
calc();
sc.push(ch[i]);
}
}
if(flag)
{
s.push(temp);
flag=0;
}
while(!sc.empty())
calc();
cout<<s.top()<<endl;
return 0;
}