[NYOJ 43] 24 Point game

时间:2023-03-09 22:16:10
[NYOJ 43] 24 Point game

24 Point game

时间限制:3000 ms  |  内存限制:65535 KB
难度:5
描述

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。

输入
The input has multicases and each case contains one line
The first line of the input is an non-negative integer C(C<=100),which indicates the number of the cases.
Each line has some integers,the first integer M(0<=M<=5) is the total number of the given numbers to consist the expression,the second integers N(0<=N<=100) is the number which the value of the expression should be.
Then,the followed M integer is the given numbers. All the given numbers is non-negative and less than 100
输出
For each test-cases,output "Yes" if there is an expression which fit all the demands,otherwise output "No" instead.
样例输入

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[]; void DFS(int num,double now)
{
if(flag) return;
if(num==n+ && fabs(now-s)<=EPS)
{
flag=;
return;
}
for(int i=;i<=n;i++)
{
if(!vis[i])
{
for(int j=;j<=;j++)
{
vis[i]=;
if(j==) DFS(num+,now+a[i]);
if(j==) DFS(num+,now-a[i]);
if(j==) DFS(num+,a[i]-now);
if(j==) DFS(num+,now*a[i]);
if(j== && a[i]) DFS(num+,now*1.0/a[i]);
if(j== && now) DFS(num+,a[i]*1.0/now);
vis[i]=;
}
}
}
} int main()
{
int T,i;
scanf("%d",&T);
while(T--)
{
flag=;
scanf("%d%lf",&n,&s);
for(i=;i<=n;i++)
{
scanf("%lf",&a[i]);
}
for(i=;i<=n;i++)
{
memset(vis,,sizeof(vis));
vis[i]=;
DFS(,a[i]);
if(flag) break;
}
if(flag)
cout<<"Yes\n";
else
cout<<"No\n";
}
return ;
}