CCF 201903-2 二十四点【枚举法】

目录

一、题目

CCF 201903-2 二十四点【枚举法】

二、解析

枚举法:
由题可知,输入固定为7个字符:d1、s1、d2、s2、d3、s3、d4。
其中,d1、d2、d3、d4是数字,s1、s2、s3是运算符号。
设运算符号x、/的等级为1,+、-的等级为0,则s1、s2、s3的组合有:
000 -> 0
001 -> 1
010 -> 10
011 -> 11
100 -> 100
101 -> 101
110 -> 110
111 -> 111
共8种。
枚举这8种运算即可。

三、代码

#include <iostream>
#include <map>

using namespace std;

int n;

int d1, d2, d3, d4;

char s1, s2, s3;

//运算符号的等级 
map<char, int> rank;

int cal(int n1, char s, int n2)
{
	int answer;
	switch (s) {
	case 'x':
		answer = n1 * n2;
		break;
	case '/':
		answer = n1 / n2;
		break;
	case '+':
		answer = n1 + n2;
		break;
	case '-':
		answer = n1 - n2;
		break;
	}
	return answer;
}

void calculate()
{
	int type = rank[s1] * 100 + rank[s2] * 10 + rank[s3];
	//cout<<type<<endl;
	int points;
	switch (type) {
	case 0:
		points = cal(cal(cal(d1, s1, d2), s2, d3), s3, d4);
		break;
	case 1:
		points = cal(cal(d1, s1, d2), s2, cal(d3, s3, d4));
		break;
	case 10:
		points = cal(cal(d1, s1, cal(d2, s2, d3)), s3, d4);
		break;
	case 11:
		points = cal(d1, s1, cal(cal(d2, s2, d3), s3, d4));
		break;
	case 100:
		points = cal(cal(cal(d1, s1, d2), s2, d3), s3, d4);
		break;
	case 101:
		points = cal(cal(d1, s1, d2), s2, cal(d3, s3, d4));
		break;
	case 110:
		points = cal(cal(cal(d1, s1, d2), s2, d3), s3, d4);
		break;
	case 111:
		points = cal(cal(cal(d1, s1, d2), s2, d3), s3, d4);
		break;
	}
	//cout<<points<<endl;
	if (points == 24)
		cout << "Yes" << endl;
	else
		cout << "No" << endl;
}

int main()
{
	rank['x'] = 1;
	rank['/'] = 1;
	rank['+'] = 0;
	rank['-'] = 0;

	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> d1 >> s1 >> d2 >> s2 >> d3 >> s3 >> d4;
		//cout<<d1<<s1<<d2<<s2<<d3<<s3<<d4<<endl;
		calculate();
	}

	return 0;
}

输入:

10
9+3+4x3
5+4x5x5
7-9-9+8
5x6/5x4
3+5+7+9
1x1+9-9
1x9-5/9
8/5+6x9
6x7-3x6
6x4+4/5

输出:

Yes
No
No
Yes
Yes
No
No
No
Yes
Yes
上一篇:博客使用与比赛推荐


下一篇:iOS便捷开发工具分享