uva 10400 Game Show Math(记忆化搜索)
2013-08-24 00:18
381 查看
题目连接:10400 - Game Show Math
题目大意:给出n个数值,可以任意的在数值之间添加+,- ,* ,/,运算,要求找到一个算式可以使得算式的值等于目标值。
注意:1、算式的运算符没有优先级,都是从左到右结合。
2、数值之间的位置不能更换,也就是说数值的顺序是确定的,只能修改运算符。
3、运算的过程中不能出现运算值的绝对值大于32000的。
解题思路:最开始想到的是递归,没有想到好的剪枝, 就直接递归下去了,结果就超时了,后来看了别人的题解后知道要用记忆化搜索。就是记录住当前前n个数字通过任意的运算所的到的sum, 如果这个sum被判定为不能达成目标, 那么另外一种不同的运算方式使得前n个的sum等于前面判定过的,那么剪掉这条枝,因为它已经不可能到达了。
题目大意:给出n个数值,可以任意的在数值之间添加+,- ,* ,/,运算,要求找到一个算式可以使得算式的值等于目标值。
注意:1、算式的运算符没有优先级,都是从左到右结合。
2、数值之间的位置不能更换,也就是说数值的顺序是确定的,只能修改运算符。
3、运算的过程中不能出现运算值的绝对值大于32000的。
解题思路:最开始想到的是递归,没有想到好的剪枝, 就直接递归下去了,结果就超时了,后来看了别人的题解后知道要用记忆化搜索。就是记录住当前前n个数字通过任意的运算所的到的sum, 如果这个sum被判定为不能达成目标, 那么另外一种不同的运算方式使得前n个的sum等于前面判定过的,那么剪掉这条枝,因为它已经不可能到达了。
#include <stdio.h> #include <string.h> #include <stdlib.h> const int N = 105; const int M = 32000; const char sign[] = "+-*/"; int n, num , order, vis [2 * M + 10]; char str ; int count(int sum, char c, int number) { if (c == '+') return sum + number; else if (c == '-') return sum - number; else if (c == '*') return sum * number; else if (c == '/') return sum / number; return 0; } int find(int sum, int deep) { if (deep == n) { if (sum == order) { str[deep - 1] = '='; return true; } else return false; } int cur; for (int i = 0; i < 4; i++) { if (i == 3 && (num[deep] == 0)) continue; cur = count(sum, sign[i], num[deep]); if (cur < -32000 || cur > 32000) continue; if (vis[deep][cur + M]) continue; if (find(cur, deep + 1)) { str[deep - 1] = sign[i]; return true; } vis[deep][cur + M] = 1; } return false; } int main () { int cas, flag; scanf("%d", &cas); while (cas--) { memset(str, 0, sizeof(str)); memset(vis, 0, sizeof(vis)); scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &num[i]); scanf("%d", &order); if (find(num[0], 1)) { for (int i = 0; i < n; i++) printf("%d%c", num[i], str[i]); printf("%d\n", order); } else printf("NO EXPRESSION\n"); } return 0; }
相关文章推荐
- UVA 10400 Game Show Math (dfs + 记忆化搜索)
- uva10400 - Game Show Math(回溯+剪枝)
- UVa 10400 - Game Show Math 游戏中的数学 dfs+判重
- UVA10400- Game Show Math
- UVa 10400 - Game Show Math
- uva 10400 - Game Show Math
- UVA 10400 - Game Show Math
- UVa 10400 - Game Show Math
- uva 10400 Game Show Math
- Uva 10400 Game Show Math (DP+记录路径)
- UVA 10400 Game Show Math
- Game Show Math - UVa10400 搜索
- uva 10400 - Game Show Math
- uva 10400 Game Show Math
- UVa 10400 - Game Show Math
- Uva 10400 —Game Show Math(深搜+剪枝)
- uva 10400 - Game Show Math
- UVA - 10400 Game Show Math(回溯)
- uva 10400(Game Show Math) (DP)
- UVa 10400 - Game Show Math