标签:dfs
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。
2 4 24 3 3 8 8 3 24 8 3 3
Yes No
分析:可以进行的运算为加, 减, 被减, 乘, 除, 被除六种运算,我们只需要每次都取出没有用的两个数(可以是运算之后的值),进行运算,枚举就好了。
代码:
#include <cstdio> #include <cstring> #include <cmath> const double E = 1e-6; using namespace std; double s[50], res; bool vis[50]; int dfs(int m, int top){ //每次取出两个数然后将结果放入数组中,就等于每次减掉一个没有使用的数 if(m == 1){ if(fabs(res - s[top-1]) < E){ //printf("%lf...res %lf..sll\n", s[top-1], res); return 1; } return 0; } for(int i = 0; i < top-1; ++ i){ if(!vis[i]){ vis[i] = 1; for(int j = i+1; j < top; ++ j){ if(!vis[j]){ vis[j] = 1; s[top] = s[i]+s[j]; if(dfs(m-1, top+1)) return 1; s[top] = s[i]-s[j]; if(dfs(m-1, top+1)) return 1; s[top] = s[j]-s[i]; if(dfs(m-1, top+1)) return 1; s[top] = s[i]*s[j]; if(dfs(m-1, top+1)) return 1; if(s[i] != 0){ s[top] = s[j]/s[i]; if(dfs(m-1, top+1)) return 1; } if(s[j] != 0){ s[top] = s[i]/s[j]; if(dfs(m-1, top+1)) return 1; } vis[j] = 0; } } vis[i] = 0; } } return 0; } int main(){ int t; scanf("%d", &t); while(t --){ int n; scanf("%d", &n); scanf("%lf", &res); for(int i = 0; i < n; ++ i) scanf("%lf", &s[i]); memset(vis, 0, sizeof(vis)); if(dfs(n, n)) printf("Yes\n"); else printf("No\n"); } return 0; }
标签:dfs
原文地址:http://blog.csdn.net/shengweisong/article/details/44419361