1. 程式人生 > >nyoj43 24 Point game(DFS)

nyoj43 24 Point game(DFS)

ssi list find memory ont abs value http outside

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
來源
經典改編
上傳者
張雲聰

感覺很經典的一道深搜題。

昨天下午自己起初給sum定義了一個初始值0。後來發現第二個測試用例不正確。

。那時候實在是不知道哪裏錯了

以至於昨天晚上做夢都夢到自己AC了這道題 哈哈技術分享技術分享

我自己認為自己的方法沒有錯。於是今天早上就百度搜搜,發現沒人和我的思想一樣技術分享

技術分享....別人都說是編程之美這本書上的。

。但是我也沒看過

他們的思想都是在一個長度為n的數組中找到隨意兩個數。然後求和,然後把和再插入數組中。同一時候n--。

直到n=1.

o(︶︿︶)o ,我就僅僅好關閉了百度。

看著自己的程序慢慢調試,而且輸出每個可能的結果值。

。後來還真被我發現了。。

由於我初始的sum為0的緣故,

假設僅僅有一個元素5,本來該僅僅有一個結果的。。但是因為我的原因會出現0-5=-5,0+5=5,0*5=0。0/5=0。

。。。傻了傻了。。

於是就又改了下AC了 。。嘿嘿。看來我的夢還是挺靈驗的。。

看代碼吧:

#include <stdio.h>
#include <math.h>
#include <string.h>
int flag,n;
double a[10],aim;//double型的把 由於相除嘛 難免會造成精度損失
int vis[10];
void dfs(double sum)
{
	int cnt=0;
	for(int i=0;i<n;i++)
	if(vis[i])
	cnt++;
	if(cnt==n&&fabs(sum-aim)<0.0000001)//一個推斷的條件。

當全部元素都用上。

並且sum和aim相差非常小 { flag=1; return ; } for(int i=0;i<n;i++) { if(!vis[i]&&!flag) { vis[i]=1; dfs(sum+a[i]);// dfs(sum-a[i]);// dfs(sum*a[i]);// dfs(sum/a[i]);// dfs(a[i]/sum);// dfs(a[i]-sum);//對於這個數sum僅僅能有6種情況 vis[i]=0; } } } int main() { int ncase; scanf("%d",&ncase); while(ncase--) { scanf("%d %lf",&n,&aim); for(int i=0;i<n;i++) scanf("%lf",&a[i]); flag=0; for(int i=0;i<n;i++)// { memset(vis,0,sizeof(vis)); vis[i]=1; if(!flag) dfs(a[i]);//起初的sum不應該為0,應該是數組中的某一個數、、 }//起初我沒有上面這個for循環,僅僅有一個dfs(0);華麗麗的wa... if(flag) printf("Yes\n"); else printf("No\n"); } return 0; }



update:在杭電上做了一道題 今天細致想了想 這道題我的做法始終還是有些欠缺。即使能在nyoj上A了。

所以讀者自行取舍。我還是忽略了 比方1 13 5 9 我的程序是執行不出來的。由於我的程序在運算的時候一定要和當前的結果有關。

所以假設想學習新知識看我在杭電上的題解把點擊打開鏈接這兩道題一樣。也當鞏固一下知識。


nyoj43 24 Point game(DFS)