1600: Twenty-four point
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 530 Solved: 86
[ Submit][ Status][ Web Board]
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.
Source
今天碰巧看到《编程之美》这本书上对这道题有详细的讲解。
拿来练习练习。
#include <stdio.h>
#include <math.h>
const int MAXN=4;
double nums[MAXN];
bool isSolve=false;
void dfs(int n)
{
if(isSolve)
return;
if(n==1&&fabs(nums[0]-24)<=1e-10)
{
isSolve=true;
return;
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
double a=nums[i];
double b=nums[j];
nums[j]=nums[n-1];
nums[i]=a+b;
dfs(n-1);
nums[i]=a-b;
dfs(n-1);
nums[i]=b-a;
dfs(n-1);
nums[i]=a*b;
dfs(n-1);
if(a!=0)
{
nums[i]=b/a;
dfs(n-1);
}
if(b!=0)
{
nums[i]=a/b;
dfs(n-1);
}
nums[i]=a;
nums[j]=b;
}
}
}
int main()
{
while(scanf("%lf%lf%lf%lf",&nums[0],&nums[1],&nums[2],&nums[3])>0)
{
isSolve=false;
dfs(4);
if(isSolve)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}
/**************************************************************
Problem: 1600
User: 0905130123
Language: C++
Result: Accepted
Time:156 ms
Memory:964 kb
****************************************************************/