Problem Description
速算24点相信绝大多数人都玩过。就是随机给你四张牌,包括A(1),2,3,4,5,6,7,8,9,10,J(11),Q(12),K(13)。要求只用'+','-','*','/'运算符以及括号改变运算顺序,使得最终运算结果为24(每个数必须且仅能用一次)。游戏很简单,但遇到无解的情况往往让人很郁闷。你的任务就是针对每一组随机产生的四张牌,判断是否有解。我们另外规定,整个计算过程中都不能出现小数。
Input
每组输入数据占一行,给定四张牌。
Output
每一组输入数据对应一行输出。如果有解则输出"Yes",无解则输出"No"。
Sample Input
A 2 3 6 3 3 8 8
Sample Output
Yes No
啊这么一道破搜索题,我的YES、NO全部是大写,然后就WA了一下午…啊啊啊啊啊啊!
搜索主要是看先来的数字与哪部分计算吧,然后全排列使用了algorithm里面的next_permutation
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int num[4];
int flag;
void DFS(int sum, int cur, int n)
{
if (flag == 1)
return;
if (n == 3)
{
if (sum + cur == 24 || sum - cur == 24 || sum * cur == 24)
flag = 1;
if (cur != 0)
if (sum % cur == 0)
if (sum / cur == 24)
flag = 1;
return;
}
DFS(sum + cur, num[n+1], n+1);
DFS(sum - cur, num[n+1], n+1);
DFS(sum * cur, num[n+1], n+1);
if (cur != 0)
if (sum % cur == 0)
DFS(sum / cur, num[n+1], n+1);
DFS(sum, cur + num[n+1], n+1);
DFS(sum, cur - num[n+1], n+1);
DFS(sum, cur * num[n+1], n+1);
if (num[n+1] != 0)
if (cur % num[n+1] == 0)
DFS(sum, cur / num[n+1], n+1);
}
int main()
{
char str[10];
while (scanf("%s", str) != EOF)
{
int len = strlen(str);
if (len == 2)
num[0] = 10;
else
{
if (str[0] == 'A')
num[0] = 1;
else if (str[0] == 'J')
num[0] = 11;
else if (str[0] == 'Q')
num[0] = 12;
else if (str[0] == 'K')
num[0] = 13;
else
num[0] = str[0] - '0';
}
for (int i = 1; i < 4; ++i)
{
scanf("%s", str);
len = strlen(str);
if (len == 2)
num[i] = 10;
else
{
if (str[0] == 'A')
num[i] = 1;
else if (str[0] == 'J')
num[i] = 11;
else if (str[0] == 'Q')
num[i] = 12;
else if (str[0] == 'K')
num[i] = 13;
else
num[i] = str[0] - '0';
}
}
flag = 0;
sort(num, num+4);
DFS(num[0], num[1], 1);
while (next_permutation(num, num + 4) && flag == 0)
DFS(num[0], num[1], 1);
if (flag == 1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}