【USACO题库】2.3.3 Zero Sum和为零

题目描述

请考虑一个由1到N(N=3, 4, 5 … 9)的数字组成的递增数列:1 2 3 … N。

现在请在数列中插入“+”表示加,或者“-”表示减,抑或是“ ”表示空白,来将每一对数字组合在一起(请不在第一个数字前插入符号)。

计算该表达式的结果并注意你是否得到了和为零。

请你写一个程序找出所有产生和为零的长度为N的数列。

PROGRAM NAME: zerosum

INPUT FORMAT

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

SAMPLE INPUT (file zerosum.in)

7

OUTPUT FORMAT

按照ASCII码的顺序,输出所有在每对数字间插入“+”, “-”, 或 “ ”后能得到和为零的数列。(注意:就算两个数字之间没有插入符号也应该保留空格)

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

题解:首先,此题第一眼就是一个很水的dfs。(若是你要用bfs也是可以的)但是,本题有一个连起来的东东,这就有点麻烦了。
我们记录下它们各个数之间的运算符,加用1,减用-1,空格随意。于是乎,就去dfs枚举一下运算符,然后就很简单啦。
标程:

var
        a:array[0..100] of longint;
        i,j,k,l,n,m:longint;
procedure dfs(dep,pd,n:longint);
var
        x,y,t,p:longint;
begin
        a[dep-1]:=pd;
        if dep>n then
        begin
                x:=1;
                y:=0;
                repeat
                        t:=x;
                        p:=a[x];
                        while (a[x+1]=0) and (x<n) do
                        begin
                                inc(x);
                                t:=t*10+x;
                        end;
                        y:=y+p*t;
                        inc(x);
                until x>n;
                if y=0 then
                begin
                        write(1);
                        for i:=2 to n do
                        begin
                                if a[i]=1 then write('+');
                                if a[i]=-1 then write('-');
                                if a[i]=0 then write(' ');
                                write(i);
                        end;
                        writeln;
                end;
                exit;
        end
        else
        begin
                inc(dep);
                dfs(dep,0,n);
                dfs(dep,1,n);
                dfs(dep,-1,n);
                dec(dep);
        end;
end;
begin
        readln(n);
        dfs(2,1,n);
end.
posted @ 2017-04-05 19:44  RainbowCrown  阅读(204)  评论(0编辑  收藏  举报