USACO-Zero Sum

本文介绍了一个通过编程解决特定数学问题的方法:寻找1到N之间的数字序列,这些序列使用+、-或空格连接,使得最终计算结果为0,并按字典序输出所有可能的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Consider the sequence of digits from 1 through N (where N=9) in increasing order: 1 2 3 … N.

Now insert either a +' for addition or a-’ for subtraction or a ` ’ [blank] to run the digits together between each pair of digits (not in front of the first digit). Calculate the result that of the expression and see if you get zero.

Write a program that will find all sequences of length N that produce a zero sum.

PROGRAM NAME: zerosum

INPUT FORMAT

A single line with the integer N (3 <= N <= 9).
SAMPLE INPUT (file zerosum.in)

7
OUTPUT FORMAT

In ASCII order, show each sequence that can create 0 sum with a +',-‘, or ` ’ between each pair of numbers.
SAMPLE OUTPUT (file zerosum.out)

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

题意:1-N的数字,用+、-、空格来组合,按字典序输出最后结果为0的方法。空格表示将相邻的两个数连起来,比如说1-2 3,就是1-23。

DFS将每种情况走一次。step表示走到哪个数了,sum表示当前和,num表示当前DFS的数。

代码:

/*
ID:iam666
PROG:zerosum
LANG:C++
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
int n,m;
void dfs(int step,int sum,int num,string s)
{
    string s1=s;
    if(step==n)
    {
        if(num+sum==0)
        {
            cout<<s<<endl;
            //return;
        }
        return ;
    }
    if(num>0)
    {
        //printf("%d %d %d\n",step,sum,num);
        //cout<<s<<endl;
        dfs(step+1,sum,num*10+step+1,s+" "+char(1+step+48));
    }
    else
    dfs(step+1,sum,num*10-step-1,s+" "+char(1+step+48));

    dfs(step+1,sum+num,step+1,s+"+"+char(step+1+48));
    dfs(step+1,sum+num,-1*step-1,s+"-"+char(step+1+48));    
}
int main (void)
{
//  freopen("zerosum.in","r",stdin);
//  freopen("zerosum.out","w",stdout);
    cin>>n;
    dfs(1,0,1,"1");
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值