标签:problem space 括号 style cout exp sed led else
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<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; }
标签:problem space 括号 style cout exp sed led else
原文地址:http://www.cnblogs.com/joeylee97/p/6838045.html