标签:style blog io color os ar for sp div
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
受不了,这么水的题搞了好久 - -,简直不能忍、
注意几个问题:
A: 括号怎么处理?由于可以乱排,我们搜索就相当于加了括号了,比如题目的 8/(3-8/3),我们搜索从8开始,8/3=2.6667,再3-2.6667=0.3333,再8/0.33333=24
B:注意加乘无方向,减和除有方向,所以有6个方向
C:注意最后判断结果的时候由于是浮点数,所以加一个精度,一般1e-8就可以了
见渣代码:
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> using namespace std; #define EPS 1e-8 #define N 10 int n; int flag; int vis[N]; double s,a[10]; void DFS(int num,double now) { if(flag) return; if(num==n+1 && fabs(now-s)<=EPS) { flag=1; return; } for(int i=1;i<=n;i++) { if(!vis[i]) { for(int j=1;j<=6;j++) { vis[i]=1; if(j==1) DFS(num+1,now+a[i]); if(j==2) DFS(num+1,now-a[i]); if(j==3) DFS(num+1,a[i]-now); if(j==4) DFS(num+1,now*a[i]); if(j==5 && a[i]) DFS(num+1,now*1.0/a[i]); if(j==6 && now) DFS(num+1,a[i]*1.0/now); vis[i]=0; } } } } int main() { int T,i; scanf("%d",&T); while(T--) { flag=0; scanf("%d%lf",&n,&s); for(i=1;i<=n;i++) { scanf("%lf",&a[i]); } for(i=1;i<=n;i++) { memset(vis,0,sizeof(vis)); vis[i]=1; DFS(2,a[i]); if(flag) break; } if(flag) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
标签:style blog io color os ar for sp div
原文地址:http://www.cnblogs.com/hate13/p/4067490.html