uva 10400 Game Show Math
来源:互联网 发布:想学游戏编程 编辑:程序博客网 时间:2024/05/22 02:03
dfs题目,注意记录状态进行剪枝,否则会超时。
#include <stdio.h>#include <set>using namespace std;#defineADD0#defineSUB1#defineMUL2#defineDIV3int arr[120];char path[120];bool stop;int max_index;int target_value;long long _hash(int cur, int value){return value*120 + cur;}set<long long> hash_map;void dfs(int oper, int cur, int last_value){if(stop)return;if(cur == max_index+1){if(last_value == target_value)stop = true;return;}int cur_value;long long hv;if(last_value<-32000 || last_value>32000)return;if(oper==DIV && last_value%arr[cur]!=0)return;switch(oper){case ADD:cur_value = last_value + arr[cur];path[cur] = '+';break;case SUB:cur_value = last_value - arr[cur];path[cur] = '-';break;case MUL:cur_value = last_value * arr[cur];path[cur] = '*';break;case DIV:cur_value = last_value / arr[cur];path[cur] = '/';break;}hv = _hash(cur, cur_value);if(hash_map.find(hv) == hash_map.end())hash_map.insert(hv);elsereturn;dfs(ADD, cur+1, cur_value);dfs(SUB, cur+1, cur_value);dfs(MUL, cur+1, cur_value);dfs(DIV, cur+1, cur_value);}void func(int n, int target){int i;hash_map.clear();stop = false;target_value = target;max_index = n-1;dfs(ADD, 1, arr[0]);dfs(SUB, 1, arr[0]);dfs(MUL, 1, arr[0]);dfs(DIV, 1, arr[0]);if(stop){printf("%d", arr[0]);for(i=1; i<=n-1; i++)printf("%c%d", path[i], arr[i]);printf("=%d\n", target);}else{printf("NO EXPRESSION\n");}}int main(void){int n, m, i;int target;//freopen("input.dat", "r", stdin);scanf("%d", &m);while(m--){scanf("%d", &n);for(i=0; i<n; i++)scanf("%d", arr+i);scanf("%d", &target);func(n, target);}return 0;}
- 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
- 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
- uva 10400(Game Show Math) (DP)
- UVA - 10400 Game Show Math(回溯)
- UVA - 10400 Game Show Math DFS
- uva 10400 Game Show Math(深搜 )
- C++ Unicode 写文件流问题
- Java IO流学习总结
- HTC one 移动TD版(M7CDTU) 与 国际版(M7UL)内核区别(从配置文件入手),草稿
- solib-absolute-prefix 和solib-search-path的区别
- 一个模板单例的实现
- uva 10400 Game Show Math
- Muye Game is Coming
- MyBatis两张表字段名相同产生的问题
- java实现ping命令
- cs661 11-14-2013{{{1
- c# 学习
- ORACLE实现字段自增示例说明
- 打印菱形星号
- Flatten Binary Tree to Linked List 二叉树变成链表@LeetCode,