试题名称 | 代码长度 | 编程语言 | 评测结果 | 得分 | 时间使用 | 空间使用 |
---|---|---|---|---|---|---|
二十四点 | 1.778KB | C++ | 正确 | 100 | 15ms | 528.0KB |
关键点:
1. 中缀表达式转为前缀(或后缀)表达式,此题不考虑“(” “)”,所以比较简单。
2. 处理字符时,注意区别应该是char类型还是int类型。
3. 运算符的优先级可以用map。
#include <stdio.h>
#include <iostream>
#include <stack>
#include <map>
using namespace std;
map<char, int> priority;
int main(){
priority['+'] = 1;
priority['-'] = 1;
priority['x'] = 2;
priority['/'] = 2;
//freopen("201903-2-24.txt","r", stdin);
int n;
scanf("%d", &n);
char line[8], pre[8];
for(int i=0; i<n; ++i){
scanf("%s", line);
stack<char> s1, s2;
char tmp;
for(int j=6; j>=0; --j){
tmp = line[j];
if(tmp>='0' && tmp<='9'){
s2.push(tmp);
}else{
while( !s1.empty() && priority[tmp] < priority[s1.top()]){
s2.push(s1.top());
s1.pop();
}
if(s1.empty() || priority[tmp] >= priority[s1.top()])
s1.push(tmp);
}
}
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
int m = 0;
while(!s2.empty()){
pre[m++] = s2.top();
s2.pop();
}
int ans;
stack<int> s3;
for(int j=6; j>=0; --j){
char tmp = pre[j];
if(tmp >= '0' && tmp <= '9'){
s3.push(tmp-'0');
}else{
int c1 = s3.top();
s3.pop();
int c2 = s3.top();
s3.pop();
if(tmp == '+'){
ans = c1 + c2;
}else if(tmp == '-'){
ans = c1 - c2;
}else if(tmp == 'x'){
ans = c1 * c2;
}else{
ans = c1 / c2;
}
s3.push(ans);
}
}
if(ans == 24){
printf("Yes\n");
}else{
printf("No\n");
}
}
return 0;
}