24 point game
24 Point game
时间限制:3000 ms | 内存限制:65535 KB
难度:5
- 描述
-
There is a game which is called 24 Point game.
In this game , you will be given some numbers. Your task is to find an expression which have all the given numbers and the value of the expression should be 24 .The expression mustn't have any other operator except plus,minus,multiply,divide and the brackets.
e.g. If the numbers you are given is "3 3 8 8", you can give "8/(3-8/3)" as an answer. All the numbers should be used and the bracktes can be nested.
Your task in this problem is only to judge whether the given numbers can be used to find a expression whose value is the given number。
- 输入
- The input has multicases and each case contains one line
The first line of the input is an non-negative integer C(C<=100),which indicates the number of the cases.
Each line has some integers,the first integer M(0<=M<=5) is the total number of the given numbers to consist the expression,the second integers N(0<=N<=100) is the number which the value of the expression should be.
Then,the followed M integer is the given numbers. All the given numbers is non-negative and less than 100 - 输出
- For each test-cases,output "Yes" if there is an expression which fit all the demands,otherwise output "No" instead.
- 样例输入
-
2 4 24 3 3 8 8 3 24 8 3 3
- 样例输出
-
Yes No
View Code1 #include <bits/stdc++.h> 2 using namespace std; 3 double num[6]; 4 int cnt, targe; 5 6 //用递归解题, 参数step,表示当前还剩几个数 7 bool dfs(int step); 8 int main() 9 { 10 int tcase; 11 cin>>tcase; 12 while(tcase--) 13 { 14 cin>>cnt>>targe; 15 for(int i=0; i<cnt; i++) cin>>num[i]; 16 if(dfs(cnt)) cout<<"Yes"<<endl; 17 else cout<<"No"<<endl; 18 } 19 return 0; 20 } 21 bool dfs(int step) 22 { 23 //当没有数的时候为错误 24 if(step == 0) return false; 25 //当只有一个数的时候,表示所有的数通过各种方式组合成了一个数,判断是否与目的数相同。 26 //因为浮点数又误差,所以相差为1e-6时候就看作相同。 27 if(step == 1) 28 { 29 if(fabs(num[0] - targe) < 1e-6) 30 return true; 31 return false; 32 } 33 34 //从剩下的step个数中取两个数 35 for(int i=0; i<step; i++) 36 { 37 for(int j=i+1; j<step; j++) 38 { 39 double a = num[i], b = num[j]; 40 //因为两个数组合为一个数后,会有一个空的空间,每次把数组的最后一个空间删去 41 //所以每次把最后一个数放到num[j]空间里,把组合好的数放到 j 的前空间 i 处。 42 num[j] = num[step-1]; 43 num[i] = a*b; if(dfs(step-1)) return true; 44 num[i] = a+b; if(dfs(step-1)) return true; 45 num[i] = a-b; if(dfs(step-1)) return true; 46 num[i] = b-a; if(dfs(step-1)) return true; 47 if(a) { num[i] = b/a; if(dfs(step-1)) return true; } 48 if(b) { num[i] = a/b; if(dfs(step-1)) return true; } 49 50 num[i] = a; 51 num[j] = b; 52 } 53 } 54 return false; 55 }


浙公网安备 33010602011771号