CSU-ACM2017暑期训练4-dfs F

来源:互联网 发布:网络门禁模块 编辑:程序博客网 时间:2024/05/17 06:28

题目:

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 91 1 1 1 5 5 5 1
Sample Output
YesNoYes
Hint

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

          

              题意:给你四个数,问你能否经过一系列+-*/运算使得结果为24.

              思路:用a[4】存数据,搜索时每两个两个进行计算,并且把结果放到下标小的里面,下标大的用他后面一个代替。

代码:


#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<string>#include<vector>#include<stack>#include<bitset>#include<cstdlib>#include<cmath>#include<set>#include<list>#include<deque>#include<map>#include<queue>using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int maxn = 100;int T,n,m;int flag;double a[4];void dfs(int step){    if(flag)        return;    if(step==3&&fabs(a[0]-24.0)<eps)    {        flag=1;        return;    }    else    {        for(int i=0;i<=3-step;i++)        {            if(flag)                return;            for(int j=i+1;j<=3-step;j++)            {                double x,y;                x=a[i];                y=a[j];                a[j]=a[3-step];                a[i]=x+y;                dfs(step+1);                a[i]=x-y;                dfs(step+1);                a[i]=y-x;                dfs(step+1);                a[i]=x*y;                dfs(step+1);                if(fabs(x-0)>eps)                {                    a[i]=y/x;                    dfs(step+1);                }                if(fabs(y-0)>eps)                {                    a[i]=x/y;                    dfs(step+1);                }                a[i]=x;                a[j]=y;            }        }    }}int main(){while(scanf("%lf%lf%lf%lf",&a[0],&a[1],&a[2],&a[3])!=EOF)    {        flag=0;        dfs(0);        if(!flag)            printf("No\n");        else            printf("Yes\n");    }    return 0;}


原创粉丝点击