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.

 

posted on 2013-08-22 12:12  makeecat  阅读(236)  评论(0编辑  收藏  举报