There is a game which is called 24 Point game.php
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. ios
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. express
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<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<deque> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<list> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 103 #define LLL 1000000000 #define INF 1000000009 #define eps 0.00000001 /* 給一些數字,可否用利用+-*和/ 將這些數字組成一個特定的值,能夠利用括號改變求值順序 注意到給的數字個數很小 最多5個 每次將其中兩個抽出來運算,而後將結果插入進去 */ double aim; int n, T; vector<double> v,tmp; bool f; void print(vector<double> &a) { for (int i = 0; i < a.size(); i++) { if (i) printf(" "); printf("%lf", a[i]); } cout << endl; } void dfs(int x) { if (x == 1) { //print(tmp); double che = tmp[0] - aim; if (tmp[0] - aim > -eps&&tmp[0] - aim < eps) { f = true; //cout << "sdaasddddddddddddddddddddddddddddddddddddddddddddddddddddd" << endl; } return; } //print(tmp); vector<double> h = tmp; double a, b, mul, add, sub1, sub2, div1, div2; for (int i = 0; i < x; i++) { for (int j = i + 1; j < x; j++) { tmp = h; a = tmp[i], b = tmp[j]; mul = a*b, add = a + b; sub1 = a - b, sub2 = b - a; if (a != 0.0) div1 = b / a; else div1 = INF; if (b != 0.0) div2 = a / b; else div2 = INF; tmp.erase(tmp.begin() + i); tmp.erase(tmp.begin() + j - 1); vector<double> r = tmp; for (int i = 0; i <= tmp.size(); i++) { tmp.insert(tmp.begin() + i, add); dfs(tmp.size()); tmp = r; if (f) return; tmp.insert(tmp.begin() + i, mul); dfs(tmp.size()); tmp = r; if (f) return; tmp.insert(tmp.begin() + i, sub1); dfs(tmp.size()); tmp = r; if (f) return; if (sub2-sub2>-eps&&sub1-sub2<eps) { tmp.insert(tmp.begin() + i, add); dfs(tmp.size()); tmp = r; } if (f) return; tmp.insert(tmp.begin() + i, div1); dfs(tmp.size()); tmp = r; if (f) return; if (div1-div2<eps&&div1-div2>-eps) { tmp.insert(tmp.begin() + i, div2); dfs(tmp.size()); tmp = r; } if (f) return; } } } } int main() { scanf("%d", &T); while (T--) { v.clear(); scanf("%d%lf", &n, &aim); int t; for (int i = 0; i < n; i++) { scanf("%d", &t); v.push_back(t); } f = false; tmp = v; dfs(n); if (f) printf("Yes\n"); else printf("No\n"); } return 0; }