Problem A: Twenty-four point
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 414 Solved: 62
[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.
-----------------------------------
第一次去中南,今天之前还不会写搜索
思路:
初始时集合(元素可重复)中有4个数,取出两个进行四则运算,考虑顺序,减、除要算两次,即 a-b b-a a/b b/a ,加、乘 与顺序无关 , 这一步情况总数为 C(4,2) * 6 。
依此类推,进行第二步第三步,每一步结束后,集合中少一个数,直到集合中只剩一个数,判断这个数是否为 24
所有可能情况的总数为 C(4,2) * 6 * C(3,2) * 6 * 6
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const double eps=1e-6; ///最大允许误差
double num[4]; ///double!!
bool dfs(int n){ ///n代表此时数组中还剩几个数
if(n==1) {
if(fabs(num[0]-24)<eps) return true;
else return false; ///n==1 return true/false
}
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++){
double a=num[i],b=num[j];
num[j]=num[n-1];
num[i]=a-b; if(dfs(n-1)) return true;
num[i]=a+b; if(dfs(n-1)) return true;
num[i]=a*b; if(dfs(n-1)) return true;
num[i]=b-a; if(dfs(n-1)) return true;
if(a) num[i]=b/a; if(dfs(n-1)) return true; ///分母
if(b) num[i]=a/b; if(dfs(n-1)) return true;
num[i]=a,num[j]=b; ///都不满足 恢复num[i],num[j] 继续搜索
}
return false; ///不管怎么选都达不到24 此路不通
}
int main()
{
while(~scanf("%lf",&num[0])){
for(int i=1;i<4;i++)
scanf("%lf",num+i);
if(dfs(4)) printf("Yes\n");
else printf("No\n"); /// YES NO 注意大小写...
}
return 0;
}