(CSU

来源:互联网 发布:宁波百度推广公司php 编辑:程序博客网 时间:2024/06/03 03:47

(CSU - 1600)Twenty-four point

Time Limit: 1 Sec Memory Limit: 128 Mb Submitted: 737 Solved: 147

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

Hint

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

题目大意:给出四个数,通过加减乘除能否算出24点。

思路:数据这么小,直接爆搜(dfs)即可。

#include<cstdio>#include<cstring>using namespace std;const double eps=1e-8;double a[5];bool sgn(double x){    return (x>-eps&&x<eps);}bool dfs(double a[],int n)//数组中n个数是否可以算出24点 {    double b[5];    if(n==1&&sgn(a[1]-24)) return true;    for(int i=1;i<=n;i++)        for(int j=1;j<=n;j++)            if(i!=j)            {                int p=1;                memset(b,0,sizeof(b));                for(int k=1;k<=n;k++)                     if(k!=i&&k!=j) b[p++]=a[k];                for(int k=1;k<=4;k++)                {                    if(k==1) b[p++]=a[i]+a[j];                    else if(k==2) b[p++]=a[i]-a[j];                    else if(k==3) b[p++]=a[i]*a[j];                    else                    {                        if(!sgn(a[j])) b[p++]=a[i]/a[j];                    }                    if(dfs(b,n-1)) return true;                    b[--p]=0;                }            }    return false;}int main(){    while(scanf("%lf%lf%lf%lf",&a[1],&a[2],&a[3],&a[4])!=EOF)    {        if(dfs(a,4)) printf("Yes\n");        else printf("No\n");    }    return 0;}
原创粉丝点击