CCF-CSP 201903-2 二十四点

201903-2 二十四点

题目链接-201903-2 二十四点
在这里插入图片描述
解题思路
STL stack 模拟

  • 用两个栈分别存数字和运算符
  • for循环遍历表达式,如果遇到的是数字,压入数字栈
  • 由于x、/ 的优先级较高,所以当遇到 x 或 / 时,我们可以直接计算结果,然后把计算结果压入数字栈
  • 如果遇到 - ,可以将下一个数的的相反数压入数字栈,将+ 压入符号栈,这样就全部化为了加法操作,遇到 + 则直接压入符号栈
  • 所有运算结束后,数字栈中剩余的数字即为结果,判断其是否等于24即可
  • 具体操作见代码

附上代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int INF=0x3f3f3f;
string a;
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	
	int n;
	cin>>n;
	cin.ignore();
	while(n--){
		stack<char> s;
		stack<int> t;
		cin>>a;
		while(!t.empty()) t.pop();
		for(int i=0;i<a.length();i++){
			if(a[i]>='0'&&a[i]<='9')
				t.push(a[i]-'0');
			else if(a[i]=='+')
				s.push(a[i]);
			else if(a[i]=='-'){
				t.push((a[i+1]-'0')*(-1));
				s.push('+');
				i++;
			}
			else if(a[i]=='x'){
				int x=t.top();
				t.pop();
				t.push(x*(a[i+1]-'0'));
				i++;	
			}
			else if(a[i]=='/'){
				int y=t.top();
				t.pop();
				t.push(y/(a[i+1]-'0'));
				i++;
			}
		}
		while(!s.empty()){
			int num1=t.top();
			t.pop();
			int num2=t.top();
			t.pop();
			s.pop();
			t.push(num1+num2);
		}
		int ans=t.top();
		if(ans==24)
			cout<<"Yes"<<endl;
		else
			cout<<"No"<<endl;
	}
	return 0;
}
发布了125 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/104908566