问题描述
试题编号: 201903-2
试题名称: 二十四点
时间限制: 1.0s
内存限制: 512.0MB
解题重点:
分类思考不同公式的排列顺序找规律,确定运算顺序和结果存储。
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;
stack<int> S;
void gameResult(char *string){
int i,temp1,temp2,ans;
bool mark[7] = {false};//如果有已经确认过的数字的话就从堆栈中取数
for(i = 0; i < 7 ; i++){
char c = string[i];
if(c == '*'){
if(!mark[i-1]&&!mark[i+1]){ //如果符号前后的数字都没有被运算
ans = (string[i-1]-'0')*(string[i+1]-'0');
mark[i-1] = true;
mark[i + 1] = true;
S.push(ans);
}
else if(mark[i-1]&&!mark[i+1]){//符号后的数字已经被运算
mark[i+1] = true;
temp1 = S.top();
S.pop();
ans = temp1 * (string[i+1]-'0');
S.push(ans);
}
else if(!mark[i-1]&&mark[i+1]){ //符号前的数字已经被运算,将堆栈中的数字与符号后的数字运算 5+4x5x5
mark[i-1] = true;
temp1 = S.top();
S.pop();
ans = temp1 * (string[i-1]-'0');
S.push(ans);
}
else{//符号前后的数字都被放入堆栈时,取堆栈中的运算结果运算 6x4+4/5
temp1 = S.top();
S.pop();
temp2 = S.top();
S.pop();
ans = temp1 * temp2;
S.push(ans);
}
}
else if(c == '/'){
if(!mark[i-1]&&!mark[i+1]){
ans = (string[i-1]-'0') / (string[i+1]-'0');
mark[i] = true;
mark[i + 1] = true;
S.push(ans);
}
else if(mark[i-1]&&!mark[i+1]){
mark[i+1] = true;
temp1 = S.top();
S.pop();
ans = temp1 / (string[i+1]-'0');
S.push(ans);
}
else if(!mark[i-1]&&mark[i+1]){
mark[i-1] = true;
temp1 = S.top();
S.pop();
ans = temp1 / (string[i-1]-'0');
S.push(ans);
}
else{
temp1 = S.top();
S.pop();
temp2 = S.top();
S.pop();
ans = temp1 / temp2;
S.push(ans);
}
}
}
for(i = 0; i < 7 ; i++){// 运算优先级 乘除法优先于加减法
char c = string[i];
if(c == '+'){
if(!mark[i-1]&&!mark[i+1]){
ans = (string[i-1]-'0') + (string[i+1]-'0');
mark[i - 1] = true;
mark[i + 1] = true;
S.push(ans);
}
else if(mark[i-1]&&!mark[i+1]){
mark[i + 1] = true;
temp1 = S.top();
S.pop();
ans = temp1 + (string[i+1]-'0');
S.push(ans);
}
else if(!mark[i-1]&&mark[i+1]){
mark[i-1] = true;
temp1 = S.top();
S.pop();
ans = temp1 + (string[i-1]-'0');
S.push(ans);
}
else{
temp1 = S.top();
S.pop();
temp2 = S.top();
S.pop();
ans = temp1 + temp2;
S.push(ans);
}
}
else if(c == '-'){
if(!mark[i-1]&&!mark[i+1]){
ans = (string[i-1]-'0') - (string[i+1] - '0');
mark[i - 1] = true;
mark[i + 1] = true;
S.push(ans);
}
else if( mark[i-1]&&!mark[i+1]){
mark[i+1] = true;
temp1 = S.top();
S.pop();
ans = temp1 - (string[i+1]-'0');
S.push(ans);
}
else if(!mark[i-1]&&mark[i+1]){
mark[i-1] = true;
temp1 = S.top();
S.pop();
ans = temp1 - (string[i-1]-'0');
S.push(ans);
}
else{
temp1 = S.top();
S.pop();
temp2 = S.top();
S.pop();
ans = temp1 - temp2;
S.push(ans);
}
}
}
if(!S.empty()){
temp1 = S.top();
S.pop();
if(temp1 == 24){
printf("YES\n");
}
else{
printf("NO\n");
}
}
}
int main(){
int n;
char string[10000];
scanf("%d", &n);
char c = getchar();
for(int i = 0 ; i < n; i++){
gets(string);
gameResult(string);
memset(string,'\0',sizeof(string));
}
return 0;
}
代码略微粗糙,没有继续讨论运算过程可能有 x/0 的问题等可能导致程序崩溃问题,但是基本思路是有了:)