题目参考链接:杭电1427 http://acm.hdu.edu.cn/showproblem.php?pid=1427
在自行编写的暴力枚举代码TLE之后,在网上搜索了一下,得到如下简化后的暴力求解思路。
先将给你的4个数进行全排列,在这过程中,对每一个全排列去进行判断,看这种排列是否能用四则运算算出24点。若算出24点,便输出“Yes”。对于其中某一种排列a,b,c,d,设#为任意一种四则运算,则仅需讨论以下两种情况,即考虑了所有可能的运算结果。1. (a#b)#(c#d)
2. ((a#b)#c)#d
注意:在这种简化的情形下,-24也是可以的。可参考: 链接一:代码参考、 链接二:思路简化、 链接三:考虑-24。而在 链接四:简短代码版中,作者通过algorithm里的next_permutation枚举给定数组的所有排列,从而大大简化了代码。
其中next_permutation的用法参见 C++文档,有关其实现的讨论参见 stackoverflow的讨论。
整合上述信息,在杭电1427上AC的参考代码如下:
#include <iostream>
using namespace std;
const int INF = 1 << 30;
int a[4];
int res[4];
bool vis[4];
bool flag;
int deal(int x,int y,int i) //四则运算
{
switch(i)
{
case 0 : return x + y;
case 1 : return x - y;
case 2 : return x * y;
case 3 : if(y != 0 && x % y == 0) return x / y;else return INF;
}
}
bool can() //判断该种排列运用四则运算是否能算出
{
int i,j,k;
int t1,t2,t3;
for(i = 0;i < 4;i ++) //(a @ b) @ (c @ d)
{
t1 = deal(res[0],res[1],i);
if(t1 == INF) continue;
for(j = 0;j < 4;j ++)
{
t2 = deal(res[2],res[3],j);
if(t2 == INF) continue;
for(k = 0;k < 4;k ++)
{
t3 = deal(t1,t2,k);
if(t3 == 24 || t3 == -24) return 1;
}
}
}
for(i = 0;i < 4;i ++) //((a @ b) @ c) @ d
{
t1 = deal(res[0],res[1],i);
if(t1 == INF) continue;
for(j = 0;j < 4;j ++)
{
t2 = deal(t1,res[2],j);
if(t2 == INF) continue;
for(k = 0;k < 4;k ++)
{
t3 = deal(t2,res[3],k);
if(t3 == 24 || t3 == -24) return 1;
}
}
}
return 0; //都不能算出,说明无解
}
void dfs(int p) //全排列
{
if(p == 4)
{
if(can()) flag = 1;
return;
}
int i,j;
for(i = 0;i < 4;i ++)
{
if(!vis[i])
{
res[p] = a[i];
vis[i] = 1;
dfs(p + 1);
if(flag) return;
vis[i] = 0;
}
}
}
int main()
{
char s[3];
int i,j,k;
while(1)
{
for(i = 0;i < 4;i ++)
{
if(scanf("%s",s) == EOF) return 0;
if(s[0] == 'A') a[i] = 1;
else if(s[0] == 'J') a[i] = 11;
else if(s[0] == 'Q') a[i] = 12;
else if(s[0] == 'K') a[i] = 13;
else if(s[0] == '1' && s[1] == '0') a[i] = 10;
else a[i] = s[0] - '0';
}
flag = 0;
memset(vis,0,sizeof(vis));
dfs(0);
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}