描述 | |
---|---|
知识点 | 字符串,循环,函数,指针,枚举,位运算,结构体,联合体,文件操作,递归 |
运行时间限制 | 10M |
内存限制 | 128 |
输入 | 输入4张牌为字符串形式,以一个空格隔开,首尾无空格; |
输出 |
如果输入的
4
张牌中包含大小王,则输出字符串“
ERROR
”,表示无法运算;
输出的算式格式为4张牌通过+-*/四个运算符相连,中间无空格,4张牌出现顺序任意, 只要结果正确;
输出算式的运算顺序从左至右,不包含括号
,如
1+2+3*4
的结果为
24
如果存在多种算式都能计算得出24,只需输出一种即可,如果无法得出24, 则输出“NONE”表示无解。 |
样例输入 | A A A A |
样例输出 | NONE |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int Is24Game(int *a, int i, int result)
{
if (result == 24)
return 1;
else if (result > 24 || i >= 4)
return 0;
else
return Is24Game(a, i + 1, result + a[i]) ||
Is24Game(a, i + 1, result - a[i]) ||
Is24Game(a, i + 1, result * a[i]) ||
Is24Game(a, i + 1, result == 0 ? 0 : result / a[i]);
}
string poker[] = {"0", "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
int main()
{
int *a = new int[4];
for (int i = 0; i < 4; i++)
{
string str;
cin >> str;
for (int j = 1; j <= 13; j++)
{
if (str.compare(poker[j].c_str()) == 0)
{
a[i] = j;
break;
}
else if (str.compare("joker") == 0 ||
str.compare("JOKER") == 0)
{
cout << "ERROR";
return 0;
}
else
{
cout << "ERROR";
return 0;
}
}
}
sort(a, a + 4);
bool flag = false;
do
{
if (Is24Game(a, 0, 0))
{
cout << poker[a[0]] << " " << poker[a[1]] << " " << poker[a[2]] << " " << poker[a[3]];
flag = true;
break;
}
} while (next_permutation(a, a + 4));
if (!flag)
cout << "NONE";
delete[]a;
return 0;
}