weinan030416

导航

算24

给出4个小于10个正整数,你可以使用加减乘除4种运算以及括号把这4个数连接起来得到一个表达式。现在的问题是,是否存在一种方式使得得到的表达式的结果等于24。

这里加减乘除以及括号的运算结果和运算的优先级跟我们平常的定义一致(这里的除法定义是实数除法)。

比如,对于5,5,5,1,我们知道5 * (5 – 1 / 5) = 24,因此可以得到24。又比如,对于1,1,4,2,我们怎么都不能得到24。

输入

 

输入数据包括多行,每行给出一组测试数据,包括4个小于10个非负整数。最后一组测试数据中包括4个0,表示输入的结束,这组数据不用处理。

 

输出

 

 对于每一组测试数据,输出一行,如果可以得到24,输出“YES”;否则,输出“NO”。

四个数求24 可以转换为 先算两个数,再三个数求24 

两个数求24 一个数求24

缩小问题规模

递归求解

#include<iostream>
#include<cmath>
using namespace std;
#define spacesize 4
double inputnumber[spacesize+1];
#define EPS 1e-6
bool iszero(double x)
{
    return fabs(x)<=EPS;
}
bool count24(double a[],int n)
{
    if(n==1)
    {
        if(iszero(a[0]-24))
            return true;
        else
            return false;
    }
    for(int i=0;i<n-1;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            double temp[n-1]={0};
            int iTemp=0;
            for(int k=0;k<n;k++)
            {
                if((k!=i)&&(k!=j))        temp[iTemp++]=a[k];
                
                temp[iTemp]=a[i]+a[j];
                if(count24(temp,n-1))    return true;
                
                temp[iTemp]=a[i]*a[j];
                if(count24(temp,n-1))    return true;
                
                temp[iTemp]=a[i]-a[j];
                if(count24(temp,n-1))    return true;
                
                temp[iTemp]=a[j]-a[i];
                if(count24(temp,n-1))    return true;
                
                if(!iszero(a[j]))
                {
                    temp[iTemp]=a[i]/a[j];
                    if(count24(temp,n-1))    return true;
                }
                
                if(!iszero(a[i]))
                {
                    temp[iTemp]=a[j]/a[i];
                    if(count24(temp,n-1))    return true;
                }
            }
        }
    }
    return false;
}

int main()
{
    while(true)
    {
        
        for(int i=0;i<spacesize;i++)
        {
            cin>>inputnumber[i];
        }
        if(inputnumber[0]==0&&inputnumber[1]==0&&inputnumber[2]==0&&inputnumber[3]==0)    
        {
            return 0;
        }
        if(count24(inputnumber,spacesize))
        cout<<"YES"<<endl;
        else
        cout<<"NO"<<endl;
    }
}

 

 

 

posted on 2023-01-18 14:58  楠030416  阅读(66)  评论(0编辑  收藏  举报