#include <iostream>
#include <stdlib.h>
#include <malloc.h>
using namespace std;
typedef struct st1
{
char biaodashi[7];//1 中缀转后缀时存运算符 2 存储后缀
int top;
}*CharStack;
typedef struct st2
{
int operater[20];//1 后缀运算时存运算数,每个运算数间加空格
int top;
}*NumStack;
void init(CharStack y)
{
y->top=-1;
}
void push(CharStack y,char x)
{
//cout<<"jin41";
++y->top;
//cout<<"jin43";
y->biaodashi[y->top]=x;
//cout<<"jin42";
}
void pop(CharStack y,char *ch)
{
*ch=y->biaodashi[y->top];
--y->top;
}
int choose(char c)
{
if(c=='+'||c=='-')
return 1;
else if(c=='*'||c=='/')
return 2;
else return 0;
}
void numinit(NumStack y)
{
y->top=-1;
}
void numpush(NumStack y,int x)
{
++y->top;
y->operater[y->top]=x;
}
void numpop(NumStack y,int *ch)
{
*ch=y->operater[y->top];
--y->top;
}
//用后缀表达式计算
int calculate(CharStack cstack)
{
int i,sum=0;
int left,right;
NumStack temp=(NumStack)malloc(sizeof(NumStack));
numinit(temp);
for(i=0;i<7;i++)
{
//printf("jin\n");
if(cstack->biaodashi[i]<='9'&&cstack->biaodashi[i]>='0'){
numpush(temp,cstack->biaodashi[i]-'0');
//printf("jin1\n");
}
else
{
//printf("jin2\n");
numpop(temp, &right);
numpop(temp, &left);
switch(cstack->biaodashi[i])
{
case '+':
sum=left+right;
numpush(temp,sum);
//printf("sum=%d\njin3\n",sum);
break;
case '-':
sum=left-right;
numpush(temp,sum);
break;
case '*':
sum=left*right;
numpush(temp,sum);
break;
case '/':
sum=left/right;
numpush(temp,sum);
break;
}
}
}
free(temp);
//printf("%d\n",sum);
return sum;
}
int main(int argc, char** argv)
{
int i,j=0;
int n=0,k;
char biao[7];
cin>>n;
k=n;
//cout<<k;
//cout<<n<<endl;
for(j=0;j<k;j++)
{
//cout<<j<<endl;
//用于中缀转后缀 存运算符
CharStack cstack=(CharStack)malloc(sizeof(CharStack));
//用于存储后缀表达式 便于之后计算
CharStack cstack2=(CharStack)malloc(sizeof(CharStack));
init(cstack);
init(cstack2);
//printf("jin0\n");
cin>>biao;
for(i=0;i<7;i++)
{
if(biao[i]>='1'&&biao[i]<='9')
{
//cout<<"jin1";
//printf("%c",biaodashi[i]);
push(cstack2,biao[i]);
//cout<<"jin3";
}
else
{
if(choose(biao[i])<=choose(cstack->biaodashi[cstack->top]))
{
// cout<<"jin2";
while(cstack->top!=-1)
{
char ch;
pop(cstack,&ch);
//printf("%c",ch);
push(cstack2,ch);
}
push(cstack,biao[i]);
}
else{
//printf("jin3\n");
push(cstack,biao[i]);
}
}
}
while(cstack->top!=-1)
{
char ch;
pop(cstack,&ch);
//printf("%c",ch);
push(cstack2,ch);
}
// printf("\n");
//cout<<cstack2->biaodashi<<endl;
if(calculate(cstack2)==24)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
//printf("%d",j);
free(cstack);
free(cstack2);
}
return 0;
}
【CCF 201903-2 二十四点】为什么在DEVC++和CODEBLOCK都能运行成功,在CCF显示运行错误?
最新推荐文章于 2021-02-23 22:02:27 发布