• 2.3.3 Zero Sum


    Zero Sum

    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
    
    {
    ID: makeeca1
    PROG: zerosum
    LANG: PASCAL
    }
    program zerosum;
    var n:longint;
    procedure dfs(step,sum,num:longint;s:string);
    var s1:string;
    begin
      s1:=s;
      if step=n then begin if (sum+num=0) then writeln(s);exit;end;
      if num>0 then dfs(step+1,sum,num*10+step+1,s+' '+chr(step+49))
               else dfs(step+1,sum,num*10-step-1,s+' '+chr(step+49));
      dfs(step+1,sum+num,step+1,s+'+'+chr(step+49));
      dfs(step+1,sum+num,-1*step-1,s+'-'+chr(step+49));
    end;
    begin
      assign(input,'zerosum.in');reset(input);
      assign(output,'zerosum.out');rewrite(output);
      readln(n);
      dfs(1,0,1,'1');
      close(output);
    end.
  • 相关阅读:
    CodeForces
    [AHOI 2013] 差异
    BZOJ
    [校内训练20_09_15]ABC
    [校内训练20_09_10]ABC
    [校内训练20_09_08]AC
    fastIO
    [校内训练20_06_05]ABC
    [校内训练20_06_04]ABC
    [校内训练20_06_03]ABC
  • 原文地址:https://www.cnblogs.com/makeecat/p/3274585.html
Copyright © 2020-2023  润新知