【搜索】洛谷 P1473 零的数列 Zero Sum

题目描述

请考虑一个由1到N(N=3, 4, 5 … 9)的数字组成的递增数列:1 2 3 … N。 现在请在数列中插入“+”表示加,或者“-”表示减,“ ”表示空白(例如1-2 3就等于1-23),来将每一对数字组合在一起(请不要在第一个数字前插入符号)。 计算该表达式的结果并判断其值是否为0。 请你写一个程序找出所有产生和为零的长度为N的数列。

输入输出格式

输入格式:

单独的一行表示整数N (3 <= N <= 9)。

输出格式:

按照ASCII码的顺序,输出所有在每对数字间插入“+”, “-”, 或 “ ”后能得到结果为零的数列。

输入输出样例

输入样例#1:

7

输出样例#1:

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

说明

翻译来自NOCOW

USACO 2.3

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,num[15],calc[15];
char c[4]={'@',' ','+','-'},fv[15];
void read(int &x)
{
    x=0;
    char c=getchar();
    while(c<'0'||c>'9')c=getchar();
    while(c>='0'&&c<='9')
    {
        x=x*10+c-'0';
        c=getchar();
    }
}
bool judge()
{
    int end=1;
    for(int i=1;i<=n;++i)
    {
        calc[end]=num[i];
        if(fv[i-1]==' ')
        {
            int temp=calc[end-1]*10+calc[end];
            end--;
            calc[end]=temp;
        }
        end++;
    }
    end--;
//  cout<<end<<endl;
//  for(int i=1;i<=end;++i)cout<<calc[i]<<' ';
//  cout<<endl;
//  system("PAUSE");
//  for(int i=1;i<n;++i)cout<<fv[i];
//  system("PAUSE");
    int pos=1;
    for(int i=2;i<=n;i++)
    {
        if(fv[i-1]=='+')
        {
            int temp=calc[pos]+calc[pos+1];
//          cout<<calc[end-1]<<'+'<<calc[end]<<'='<<temp<<endl;
//          system("PAUSE");
            pos++;
            calc[pos]=temp;
        }
        else if(fv[i-1]=='-')
        {
            int temp=calc[pos]-calc[pos+1];
//          cout<<calc[end-1]<<'-'<<calc[end]<<'='<<temp<<endl;
//          system("PAUSE");
            pos++;
            calc[pos]=temp;
        }
    }
    if(calc[pos]==0)return true;
    return false;
}
void print()
{
    for(int i=1;i<=n;++i)
    {
        cout<<num[i];
        if(i!=n)cout<<fv[i];
    }
    cout<<endl;
}
void search(int pos)
{
    if(pos==n)
    {
        if(judge())print();
        return ;
    }
    for(register int i=1;i<=3;++i)
    {
        fv[pos]=c[i];
        search(pos+1);
    }
}
int main()
{
    read(n);
    for(register int i=1;i<=n;++i)num[i]=i;
    search(1);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值