nyoj43 24 Point game(DFS),nyoj43dfs
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.
-
範例輸入
-
24 24 3 3 8 83 24 8 3 3
-
範例輸出
-
YesNo
-
來源
-
經典改編
-
上傳者
-
張雲聰
感覺非常經典的一道深搜題。昨天下午自己起初給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");elseprintf("No\n");}return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。