标签:nyoj43
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 <stdio.h> #include <math.h> int t, n; double targ, arr[10]; bool vis[10]; double cal(double a, double b, int k){ switch(k){ case 0: return a + b; case 1: return a - b; case 2: return a * b; case 3: return a / b; case 4: return b - a; case 5: return b / a; } } bool backTrack(int num, int pos){ if(num == 1 && fabs(arr[pos] - targ) < 1e-5) return true; double tmp1, tmp2; for(int i = 0; i < n; ++i){ if(!vis[i]) for(int j = i + 1; j < n; ++j){ if(!vis[j]){ tmp1 = arr[i]; tmp2 = arr[j]; for(int k = 0; k < 6; ++k){ if(k == 3 && arr[j] == 0 || k == 5 && arr[i] == 0) continue; arr[j] = cal(arr[i], arr[j], k); vis[i] = true; if(backTrack(num - 1, j)) return true; vis[i] = false; arr[i] = tmp1; arr[j] = tmp2; } } } } return false; } int main(){ scanf("%d", &t); while(t--){ scanf("%d%lf", &n, &targ); for(int i = 0; i < n; ++i) scanf("%lf", &arr[i]); for(int i = 0; i < 10; ++i) vis[i] = false; printf(backTrack(n, n - 1) ? "Yes\n" : "No\n"); //n个元素,结束位置是n-1 } return 0; }
NYOJ43 24 Point game 【回溯】,布布扣,bubuko.com
标签:nyoj43
原文地址:http://blog.csdn.net/chang_mu/article/details/27217365