您的位置:首页 > 其它

csu 1600: Twenty-four point

2016-03-06 09:48 211 查看
传送门

1600: Twenty-four point

Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 490 Solved: 78
[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

思路:
dfs,把数组当参数,4个数先选2个算一下,然后变成三个数,传入当下一层,避免了麻烦的选数

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <stack>
#include <cctype>
#include <vector>
#include <cmath>
#include <map>
#include <queue>

#define ll long long
#define eps 1e-8

using namespace std;

double a[5];

int dfs(double p[],int len)
{
if(len==1){
if(fabs(p[0]-24)<eps){
return 1;
}
else{
return 0;
}
}
double f[5];
int cou;
int i,j,k;
for(i = 0;i <len-1;i++){
for(j=i+1;j<len;j++){
cou=0;
for(k=0;k<len;k++){
if(k!=i && k!=j){
f[cou]=p[k];cou++;
}
}
f[cou]=p[i]+p[j];
if(dfs(f,cou+1)) return 1;
f[cou]=p[i]-p[j];
if(dfs(f,cou+1)) return 1;
f[cou]=p[j]-p[i];
if(dfs(f,cou+1)) return 1;
f[cou]=p[i]*p[j];
if(dfs(f,cou+1)) return 1;
if(p[j]!=0){
f[cou]=p[i]/p[j];
if(dfs(f,cou+1)) return 1;
}
if(p[i]!=0){
f[cou]=p[j]/p[i];
if(dfs(f,cou+1)) return 1;
}
}
}
return 0;
}

int main()
{
//freopen("in.txt","r",stdin);
//scanf("%d",&T);
//for(int ccnt=1;ccnt<=T;ccnt++){
while(scanf("%lf%lf%lf%lf",&a[0],&a[1],&a[2],&a[3])!=EOF){
if(dfs(a,4) == 1){
printf("Yes\n");
}
else{
printf("No\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: