oyoj-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
24時のゲームは、カードの数が不定で、点数の和も不定です.まず配列から2つの数を取って、4はこの2つの数を演算して、結果を配列に戻して、このようにn-1のサブ問題になります.再帰的に実現する.
 
#include <iostream> 
#include <stdio.h>
#include <cmath>
#include <cstring>
#define eps 10E-6
using namespace std;

int n;
double m;
double a[110];

int dfs(int num)
{
	if(num==n)
	{
		if(abs(a[n]-m)<=eps) 
		//                  。。。。
		//   a[n] m        ,   1; 
		return 1;
		return 0;
	}
	for(int i=num;i<n;i++) 
	{
		for(int j=i+1;j<=n;j++)       
		{
			double p,q;
			q=a[i];
			p=a[j];
			
			a[i]=a[num];  //        
			
			//       
			a[j]=q+p;  
			if(dfs(num+1))
			return 1;
			
			a[j]=q-p;  //  1 
			if(dfs(num+1))
			return 1;
			
			a[j]=p-q;  //  2 
			if(dfs(num+1))
			return 1;
			
			a[j]=p*q;
			if(dfs(num+1))
			return 1;
			
			if(q)  //q!=0
			a[j]=p/q;  
			if(dfs(num+1))
			return 1;
			
			if(p) //p!=0 
			a[j]=q/p;
			if(dfs(num+1))
			return 1;
			
			a[i]=q;  
			a[j]=p;
		}
	}
	return 0;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>n>>m;
		for(int i=1;i<=n;++i)
		{
			cin>>a[i];
		}
		if(dfs(1))
		cout<<"Yes"<<endl;
		else
		cout<<"No"<<endl;
	}
	return 0;
}