计算24点

题目参考链接:杭电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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值