poj1950 深搜

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

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

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

代码:



#include<cstdio>
#include<cstring>
using namespace std;
const int N=100;
char line[N]=" 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15";
int n;
int ans=0;
void dfs(int x,int last ,int sum){
    if(x==n){
        if(sum+last==0){
            ans++;
            if(ans<21)
            puts(line+1);
        }
        return ;
    }
    if(x<=9)
    line[x*4-1]='+';
    else line[x*4-1+x-9]='+';
    dfs(x+1,x+1,sum+last);
    if(x<=9)
    line[x*4-1]='-';
    else line[x*4-1+x-9]='-';
    dfs(x+1,-x-1,sum+last);
    if(x<=9)
    line[x*4-1]='.';
    else line[x*4-1+x-9]='.';
    if(x>8)
    last=last>0?last*100+x+1:last*100-x-1;
    else last=last>0?last*10+x+1:last*10-x-1;
    dfs(x+1,last,sum);
}


int main()
{
    scanf("%d",&n);
    if(n<10) line[4*n-2]='\0';
    else line[4*n-2+n-9]='\0';
    dfs(1,1,0);
    printf("%d\n",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值