201903-2二十四点

#include<iostream>
#include<stack>
#include<ctype.h>
#include<string>
using namespace std;
struct oprt
{
	char opr;
	int clas;//运算符等级
};
oprt op[5] = { {'#',0}, {'+',1},{'-',1},{'x',3},{'/',3} };
int judge(char c)
{
	for (int i = 0; i < 5; i++)
	{
		if (op[i].opr == c)
			return op[i].clas;
	}
	return -1;
}
int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		string s;
		cin >> s;
		stack<int> nu;
		stack<char> opr;
		opr.push('#');
		for (int j = 0; j < 7; j++)//将计算表达式压入栈中,要求已有符号若大于待入符号,则先运算已有符号即可,否则压入
		{
			if (isdigit(s[j]))
			{
				nu.push(s[j]-'0');
			}
			else
			{
				if (judge(s[j]) > judge(opr.top()))
				{
					opr.push(s[j]);
				}
				else
				{
					char ct = opr.top();
					opr.pop();
					int t2 = nu.top();
					nu.pop();
					int t1 = nu.top();
					nu.pop();
					switch (ct)
					{
					case '+':nu.push(t1 + t2); break;
					case '-':nu.push(t1 - t2); break;
					case 'x':nu.push(t1 * t2); break;
					case '/':nu.push(t1 / t2); break;
					}
					opr.push(s[j]);
				}
			}
		}
		//最终形成的符号栈总下到上等级提高
		while (nu.size() > 1)
		{
			char ct = opr.top();
			opr.pop();
			int t2 = nu.top();
			nu.pop();
			int t1 = nu.top();
			nu.pop();
			switch (ct)
			{
			case '+':nu.push(t1 + t2); break;
			case '-':nu.push(t1 - t2); break;
			case 'x':nu.push(t1 * t2); break;
			case '/':nu.push(t1 / t2); break;
			}
		}
		if (nu.top() == 24)
			cout << "YES" << endl;
		else
			cout << "NO" << endl;
	}
	return 0;
}
posted @ 2019-08-09 16:06  归根复命  阅读(215)  评论(0编辑  收藏  举报