Description
请考虑一个由1到N(N=3, 4, 5 … 9)的数字组成的递增数列:1 2 3 … N。
现在请在数列中插入“+”表示加,或者“-”表示减,抑或是“ ”表示空白,来将每一对数字组合在一起(请不在第一个数字前插入符号)。
计算该表达式的结果并注意你是否得到了和为零。
请你写一个程序找出所有产生和为零的长度为N的数列。
Input
单独的一行表示整数N (3 <= N <= 9)。
Output
按照ASCII码的顺序,输出所有在每对数字间插入“+”, “-”, 或 “ ”后能得到和为零的数列。(注意:就算两个数字之间没有插入符号也应该保留空格)
Sample Input
7
Sample Output
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:
1.搜它长度为N的组合。
2.搜到一个就判断一次总和,和为零,就加入C数组中。
3.对C数组进行排序。
4.备注:N<=9,所以不用担心超时。
const
maxn=9;
a:array [1..maxn] of char=('1','2','3','4','5','6','7','8','9');
var
b:array [1..maxn,1..3] of boolean;
c:array [0..20] of string;
i,j,n,t:longint;
procedure dfs(dep,x:longint;ans:string);
var
i,k,kk:longint;
st,oo:string;
begin
if dep>n then
begin
if x=0 then
begin
inc(t);
c[t]:=copy(ans,2,length(ans)-1);
end;
exit;
end;
for i:=1 to 3 do
if b[dep,i] then
begin
b[dep,i]:=false;
case i of
1:dfs(dep+1,x+dep,ans+'+'+a[dep]);
2:dfs(dep+1,x-dep,ans+'-'+a[dep]);
3:case ans[length(ans)-1] of
'+':dfs(dep+1,x+((dep-1)*9+dep),ans+' '+a[dep]);
'-':dfs(dep+1,x-((dep-1)*9+dep),ans+' '+a[dep]);
' ':begin
st:=ans; oo:=a[dep]; k:=length(st);
while (st[k]<>'+') and (st[k]<>'-') do
begin
if st[k] in ['1'..'9'] then oo:=st[k]+oo;
dec(k);
end;
val(oo,kk);
case st[k] of
'+':dfs(dep+1,x-kk div 10+kk,ans+' '+a[dep]);
'-':dfs(dep+1,x+kk div 10-kk,ans+' '+a[dep]);
end;
end;
end;
end;
b[dep,i]:=true;
end;
end;
begin
readln(n);
fillchar(b,sizeof(b),true);
dfs(2,1,'+1');
for i:=1 to t-1 do
for j:=i+1 to t do
if c[i]>c[j] then
begin
c[0]:=c[i];c[i]:=c[j];c[j]:=c[0];
end;
for i:=1 to t do writeln(c[i]);
end.