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;}