/****自己以为自己代码差不多了,做了这道题才知道还远着呢http://acm.nyist.net/JudgeOnline/problem.php?pid=409,擦,吐槽一下,六,七个小时的受不了
*///
#include<ctype.h>
#include<cstdio>
#include<string>
#include<queue>
#include<algorithm>
#include<stack>
#include<iostream>
using namespace std;
int _pri(char s)
{
switch(s)
{
case '=':return -1;break;
case '+':return 0;break;
case '-':return 0;break;
case '*':return 1;break;
case '/':return 1;break;
case '(':return 2;break;
case ')':return 2;break;
}
}
int _using(char c)
{
switch(c)
{
case '+':return -1;break;
case '-':return -2;break;
case '*':return -3;break;
case '/':return -4;break;
}
}
double totly(double *a,int n)
{
stack <double> x;
double sum =0;
for(int i=0;i<n;i++)
{
if(a[i]>=0)
x.push(a[i]);
else
{
double a1 = x.top();
x.pop();
double a2 = x.top();
x.pop();
if(a[i]==-1)
sum=(a1+a2);
else
if(a[i]==-2)
sum=(a2-a1);
else
if(a[i]==-3)
sum=(a2*a1);
else
if(a[i]==-4)
sum=(a2/a1);
x.push(sum);
}
}
return sum;
}
int main()
{
int n,m;
double a[1000];
char _sory[1000];
int icase;
string str,str1;
stack <char> s;
stack <char> s1;
scanf("%d",&icase);
while(icase--){
string nus[1000];
cin>>str;
str1 = str;
n = str1.size();
m = 0;n-= 2;
s1.push('=');
while(n>=0&&!s1.empty()){
if(isdigit(str1[n])||str1[n]=='.'){
while(isdigit(str1[n])||str1[n]=='.')
nus[m] = str1[n--]+nus[m];
m++;
}
else{
if(str1[n]=='('){
while(!s1.empty()&&s1.top()!=')') {
nus[m++]= s1.top();
s1.pop();
}
n--;
s1.pop();
}
else
if(!s1.empty()&&_pri(s1.top())<=_pri(str1[n])){
s1.push(str1[n--]);
}
else
{
while(!s1.empty()&&_pri(s1.top())>_pri(str1[n])&&s1.top()!=')'){
nus[m++] = s1.top();
s1.pop();
}
s1.push(str1[n--]);
}
}
}
while(!s1.empty()){
nus[m++]= s1.top();
s1.pop();
}
m -= 2;
for(;m>=0;m--)
cout<<nus[m]<<" ";
cout<<"="<<endl;
int cur = 0;
char ch = *str.begin();
while(ch != '=')
{
if(ch<='9'&&ch>='0'){
int cn = 0;
while(ch<='9'&&ch>='0'||ch=='.'){
_sory[cn++] = ch;
str.erase(str.begin());
ch = *str.begin();
}
_sory[cn] = '\0';
cout<<_sory<<" ";
a[cur++] = atof(_sory);
}
else{
if(s.empty())s.push(ch);
else{
if(ch==')')
{
while(!s.empty()&&s.top()!='('){
cout<<s.top()<<" ";
a[cur++] = _using(s.top());
s.pop();
}
if(!s.empty()) s.pop();
}
else
if((_pri(s.top())<_pri(ch)))
s.push(ch);
else
{
while(!s.empty()&&_pri(s.top())>=_pri(ch)&&s.top()!='('){
cout<<s.top()<<" ";
a[cur++] = _using(s.top());
s.pop();
}
s.push(ch);
}
}
str.erase(str.begin());
ch = *str.begin();
}
}
while(!s.empty()){
cout<<s.top()<<" ";
a[cur++] = _using(s.top());
s.pop();
}
cout<<"="<<endl;
printf("%.2lf\n",totly(a,cur));
}
}
中缀式 变 前缀试,变后缀试,然后表达式求值
最新推荐文章于 2022-07-27 21:40:21 发布