SDUT 3297 DFS, sdut3297dfs
Wonderful 23 o'clock Time Limit: 1000 ms Memory limit: 65536 K any questions? Click Here ^_^ Description
The question is very simple. Five numbers are given. You can use the '+', '-', and '*' operators (the operator has no priority relationship) to make the final calculation result equal to 23, the five numbers can be changed in any order.
Enter 5 numbers in the range of [1, 50]. Output: if the final calculation result is 23, the output is Yes. If not, the output is No.
Sample Input
1 1 1 1 11 2 3 4 52 3 5 7 11
Sample output
NoYesYes
Prompt
Prompt
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<map>using namespace std;int flag=0;int vis[55];int a[6];char c[]= {'+','-','*'};int DFS(int i ,int ans,int num){ if(flag||num>5) return 0; if(ans==23&&num==5) { flag=1; return 1; } for(int j=0; j<5; j++) for(int i=0; i<3; i++) { if(vis[j]==0) { vis[j]=1; if(i==0) DFS(j,ans+a[j],num+1); else if(i==1) DFS(j,ans-a[j],num+1); else DFS(j,ans*a[j],num+1); vis[j]=0; } } return 0;}int main(){ while(~scanf("%d",&a[0])) { flag=0; for(int i=1; i<5; i++) scanf("%d",&a[i]); for(int i=0; i<5; i++) { memset(vis,0,sizeof(vis)); vis[i]=1; DFS(i,a[i],1); if(flag) break; } if(flag==0) printf("No\n"); else printf("Yes\n"); }}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.