码迷,mamicode.com
首页 > 其他好文 > 详细

CSU - 1600 : Twenty-four point

时间:2017-07-28 20:56:16      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:use   turn   put   through   rac   开始   each   action   add   

Given four numbers, can you get twenty-four through the addition, subtraction, multiplication, and division? Each number can be used only once.

 

Input

The input consists of multiple test cases. Each test case contains 4 integers A, B, C, D in a single line (1 <= A, B, C, D <= 13).

 

Output

For each case, print the “Yes” or “No”. If twenty-four point can be get, print “Yes”, otherwise, print “No”.

 

Sample Input

2 2 3 9
1 1 1 1 
5 5 5 1

Sample Output

Yes
No
Yes

Hint

For the first sample, (2/3+2)*9=24.

 

emmmmm,是一道需要姿势的题,四个数需要随机排序,开始想的很麻烦。后来看了标程发现姿势很重要。在四个数中随意选两个做四则运算保存结果作为一个新的数,将新生成的三个数重复这个操作,直到最后变成一个数,检查一个数是不是24即可。

#include<iostream>
#include<math.h>

using namespace std;

double num[4];

bool flag;

bool equel(double a, double b)
{
    if(fabs(a - b) <= 1e-10)
        return true;
    return false;
}

void DFS(int n)
{
    if(flag||(n==1&&fabs(num[0]-24)<=1e-10))
    {
        flag=true;
        return;
    }
    else
    {
        for(int i=0;i<n;i++)
            for(int j=i+1;j<n;j++)
            {
                double c1 = num[i], c2 = num[j];
                num[j] = num[n - 1];
                num[i] = c1 + c2;
                DFS(n - 1);
                num[i] = c1 - c2;
                DFS(n - 1);
                num[i] = c2 - c1;
                DFS(n - 1);
                num[i] = c1 * c2;
                DFS(n - 1);
                if(!equel(c2, 0))
                {
                    num[i] = c1 / c2;
                    DFS(n - 1);
                }
                if(!equel(c1, 0))
                {
                    num[i] = c2 / c1;
                    DFS(n - 1);
                }
                num[i] = c1;
                num[j] = c2;

            }
    }
}

int main()
{
    while(cin>>num[0]>>num[1]>>num[2]>>num[3])
    {
        flag=false;
        DFS(4);
        
        if(flag==1)
            cout<<"Yes"<<endl;
            else
                cout<<"No"<<endl;    
    }
    
    
    return 0;
}

 

CSU - 1600 : Twenty-four point

标签:use   turn   put   through   rac   开始   each   action   add   

原文地址:http://www.cnblogs.com/xibeiw/p/7252406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!