CSU

来源:互联网 发布:js正则表达式判断字母 编辑:程序博客网 时间:2024/05/16 23:49

Twenty-four point

Time limit:1000 ms Memory limit:262144 kB OS:Linux


Problem Description

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


题意:

四个数字,任意次序,通过括号和四则运算是否能得到24。

解题思路:

爆搜。在前n个数里面任选两个求出结果,把结果放到前面一个数的位置,把a[n]放到后面那个数的位置,然后搜前n-1个数,最后的结果就存在a[0].


Code:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;const double EPS=1e-8;double a[5];bool flag=false;void dfs(int n){    if(n<=0&&fabs(a[0]-24)<EPS)    {        flag=true;        return;    }    if(flag||n<=0)        return;    for(int i=0;i<=n;i++)    {        for(int j=i+1;j<=n;j++)        {            double x=a[i],y=a[j];            a[j]=a[n];            a[i]=x*y;            dfs(n-1);            a[i]=x+y;            dfs(n-1);            a[i]=x-y;            dfs(n-1);            a[i]=y-x;            dfs(n-1);            if(fabs(x)>EPS)            {                a[i]=y/x;                dfs(n-1);            }            if(fabs(y)>EPS)            {                a[i]=x/y;                dfs(n-1);            }            a[i]=x,a[j]=y;        }    }}int main(){    while(scanf("%lf%lf%lf%lf",a,a+1,a+2,a+3)!=EOF)    {        flag=false;        dfs(3);        if(flag)            printf("Yes\n");        else            printf("No\n");    }    return 0;}