Dessert
Description FJ has a new rule about the cows lining up for dinner. Not only must the N (3 <= N <= 15) cows line up for dinner in order, but they must place a napkin between each pair of cows with a "+", "-", or "." on it. In order to earn their dessert, the cow numbers and the napkins must form a numerical expression that evaluates to 0. The napkin with a "." enables the cows to build bigger numbers. Consider this equation for seven cows: 1 - 2 . 3 - 4 . 5 + 6 . 7
Input One line with a single integer, N Output One line of output for each of the first 20 possible expressions -- then a line with a single integer that is the total number of possible answers. Each expression line has the general format of number, space, napkin, space, number, space, napkin, etc. etc. The output order is lexicographic, with "+" coming before "-" coming before ".". If fewer than 20 expressions can be formed, print all of the expressions. 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 Source |
#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int maxn=101;
char str[maxn];
int n,ans,k;
/*
* sum : 已求得的表达式的值
* pre : 当前位置pos的前一位置的值
* pos : 当前处理的数字,pos-1为符号插入的位置
*/
void dfs(int sum,int pre,int pos)
{
if(pos==n+1)
{
if(sum==0)
{
ans++;
if(ans<=20)
{
for(int i=1;i<n;i++)
{
printf("%d %c ",i,str[i]);
}
printf("%d\n",n);
}
}
return;
}
str[pos-1]='+';
dfs(sum+pos,pos,pos+1);
str[pos-1]='-';
dfs(sum-pos,-pos,pos+1);
str[pos-1]='.';
if(pos>=10)
k=100;
else k=10;
if(pre<0)
dfs(sum-pre+pre*k-pos,pre*k-pos,pos+1);
else if(pre>0)
dfs(sum-pre+pre*k+pos,pre*k+pos,pos+1);
}
int main()
{
scanf("%d",&n);
ans=0;
dfs(1,1,2);
printf("%d\n",ans);
return 0;
}