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
二十四点,题意和思路都很明确,考验代码能力……
每层搜索创建一个数组,从上一层的数组中挑两个数组合,将结果和剩下的数存入新数组,传递到下一层,注意浮点数精度
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
double n[4];
bool dfs(double t[],int cot){
double a;
int i,j,k,l;
double s[4];
if(cot==1){
if(fabs(t[0]-24.0)<1e-8){
return true;
}else{
return false;
}
}
for(i=0;i<cot;i++){
for(j=0;j<cot;j++){
if(i!=j){
l=0;
for(k=0;k<cot;k++){
if(k!=i&&k!=j){
s[l]=t[k];
l++;
}
}
s[l]=t[i]+t[j];
if (dfs(s,cot-1)) return true;
s[l]=t[i]-t[j];
if (dfs(s,cot-1)) return true;
s[l]=t[j]-t[i];
if (dfs(s,cot-1)) return true;
s[l]=t[i]*t[j];
if (dfs(s,cot-1)) return true;
if(t[i]!=0){
s[l]=t[j]/t[i];
if (dfs(s,cot-1)) return true;
}
if(t[j]!=0){
s[l]=t[i]/t[j];
if (dfs(s,cot-1)) return true;
}
}
}
}
return false;
}
int main()
{
while((scanf("%lf %lf %lf %lf",&n[0],&n[1],&n[2],&n[3]))!=EOF){
if(dfs(n,4)){
printf("Yes\n");
}else{
printf("No\n");
}
}
return 0;
}