Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 5430 | Accepted: 2029 |
Description
1 - 2 . 3 - 4 . 5 + 6 . 7
This means 1-23-45+67, which evaluates to 0. You job is to assist the cows in getting dessert. (Note: "... 10 . 11 ...") will use the number 1011 in its calculation.)
Input
Output
Sample Input
7
Sample Output
1 + 2 - 3 + 4 - 5 - 6 + 7 1 + 2 - 3 - 4 + 5 + 6 - 7 1 - 2 + 3 + 4 - 5 + 6 - 7 1 - 2 - 3 - 4 - 5 + 6 + 7 1 - 2 . 3 + 4 + 5 + 6 + 7 1 - 2 . 3 - 4 . 5 + 6 . 7 6
题意:往 1 - n里面添加符号 + - . 问怎样使得结果为 0 ..输出方案数以及方案。。如果方案数>20,那么输出前20个方案。
题解:DFS太弱了。。不知道怎么处理点号。。参考别人的。多加练习深搜!
#include<cstdio> #include<cstring> #include<algorithm> #include<math.h> #include<queue> #include<iostream> using namespace std; int cnt,n; int vis[20]; char expe[30]; void dfs(int deep,int ans,int pre) { if(deep==n) { if(ans==0) { cnt++; if(cnt<=20) { for(int i=1; i<n; i++) { printf("%d %c ",i,expe[i]); } printf("%d\n",n); } } return; } else { int now,next,k; expe[deep]='+'; dfs(deep+1,ans+deep+1,deep+1); ///当前数为deep+1 ,由于是"+",得到的下一个数为ans+(deep+1) expe[deep]='-'; dfs(deep+1,ans-(deep+1),deep+1); expe[deep]='.'; if(deep+1>9) { now = 100*pre+(deep+1); } else now = 10*pre+(deep+1); int j = deep-1; while(expe[j]=='.'&&j>=0) j--; if(expe[j]=='+') dfs(deep+1,(ans-pre)+now,now); ///这里的话开始硬是没写出来 else dfs(deep+1,(ans+pre)-now,now); } return; } int main() { int t = 1; while(scanf("%d",&n)!=EOF&&n) { cnt = 0; memset(vis,0,sizeof(vis)); expe[0] = '+'; ///0+???? dfs(1,1,1); printf("%d\n",cnt); } return 0; }