这个专题很迷,因为这种东西很少使用,一般都是中缀转后缀(容易计算),但是有一些bt的题目总是喜欢这样倒着出题,所以适当的了解还是有必要的。
题目描述
给出按后缀表示法输入的一个算术表达式,表达式中只有26个大写英文字母和加减乘除四个运算符号,表达式的长度<=50,表达式以#号结束。请你编程求出它的等价中缀表达式。
输入输出格式
输入格式:
输入文件只有一行,就是后缀表达式。
输出格式:
输出文件只有一行,就是它的等价中缀表达式。
输入输出样例
输入样例#1:
AB+CD*EF-*/ #
输出样例#1:
(A+B)/(C*D*(E-F))
这道题目可以使用一个字符串栈,每一步都添加一个括号,最后再判断情况能否删除括号,然后还要做一些小小的调整,就可以AC了!我的代码写的比较丑陋……
#include<bits/stdc++.h>
using namespace std;
char s[5010][5010],c[5010];
char first[5010],second[5010];
int len[5010];
int zhan1[5010],zhan2[5010];
int cmp1(char a,char b){//a为插入的字符,b为比较
//如果可以去括号,返回0
if(a=='/')
if(b=='-' || b=='+')return 1;
else return 0;
if(a=='*')
if(b=='+' || b=='-')return 1;
else return 0;
if(a=='+')return 0;
if(a=='-')return 0;
}
int cmp2(char a,char b){//a为插入的字符,b为比较
//如果可以去括号,返回0
if(a=='/')return 1;
if(a=='*')
if(b=='+' || b=='-')return 1;
else return 0;
if(a=='+')return 0;
if(a=='-')return 0;
}
int xiao(char a,char b){
//如果a比b小,返回0
if(a=='+')return 0;
if(a=='-')return 0;
if(b=='+' || b=='-')return 1;
return 0;
}
int number;
int pd1(char ch,char a[],int lena){
char small=41;
for(int i=1;i<lena;i++){
if(a[i]=='('){
int zuo=1;
while(a[i]!=')' || zuo){
i++;
if(a[i]=='(')zuo++;
if(a[i]==')')zuo--;
}
}
if(i==lena)break;
if((a[i]=='+' || a[i]=='-' || a[i]=='*' || a[i]=='/') &&(small==')' || xiao(a[i],small)==0))
small=a[i];
}
// puts(a);printf("%c\n",small);
if(small==')')return 1;
return cmp1(ch,small);
}
int pd2(char ch,char a[],int lena){
char small=41;
for(int i=1;i<lena;i++){
if(a[i]=='('){
int zuo=1;
while(a[i]!=')' || zuo){
i++;
if(a[i]=='(')zuo++;
if(a[i]==')')zuo--;
}
}
if(i==lena)break;
if((a[i]=='+' || a[i]=='-' || a[i]=='*' || a[i]=='/') &&(small==')' || xiao(a[i],small)==0))
small=a[i];
}
if(small==')')return 1;
return cmp2(ch,small);
}
int main(){
int i,j,k,n,m,tmp=0;
char ch=getchar();
while(ch!='#'){
if(ch>='A' && ch<='Z'){
s[++tmp][0]=ch;
len[tmp]=1;
}
else if(ch=='+' || ch=='-' || ch=='*' || ch=='/'){
int lennow=1,now=tmp-1;
strcpy(first,s[tmp-1]);
s[now][0]='(';
strcpy(second,s[tmp]);
if(pd1(ch,first,len[tmp-1])==1){
//不去括号
lennow+=len[tmp-1]+1;
for(i=1;i<lennow;i++)
s[now][i]=first[i-1];
}
else{
//去括号!
lennow=lennow+len[now]-1;
for(i=1;i<len[now]-2;i++)
s[now][i]=first[i];
}
s[now][lennow-1]=ch;///!!!
int last=lennow;
if(pd2(ch,second,len[tmp])==1){
lennow+=len[tmp]+1;
for(i=last;i<lennow;i++)
s[now][i]=second[i-last];
}
else{
for(i=last;i<last+len[tmp]-1;i++)
s[now][i]=second[i-last+1];
lennow=last+len[tmp]-1;
}
tmp--;
len[tmp]=lennow;
s[tmp][lennow-1]=')';
}
ch=getchar();
}
if(s[1][len[1]-1]==')')
for(i=1;i<len[1]-1;i++)
printf("%c",s[1][i]);
else for(i=1;i<len[1];i++)
printf("%c",s[1][i]);
return 0;
}