自然数拆分
描述 Description
输入自然数n,然后将其拆分成由若干数相加的形式,参与加法运算的数可以重复。
输入格式 Input Format
输入只有一个整数n,表示待拆分的自然数n。 n<=80
输出格式 Output Format
输出一个数,即所有方案数
样例输入 Sample Input
7
样例输出 Sample Output
14
时间限制 Time Limitation
各个测试点1s
注释 Hint
解释:
输入7,则7拆分的结果是
7=1+6
7=1+1+5
7=1+1+1+4
7=1+1+1+1+3
7=1+1+1+1+1+2
7=1+1+1+1+1+1+1
7=1+1+1+2+2
7=1+1+2+3
7=1+2+4
7=1+2+2+2
7=1+3+3
7=2+5
7=2+2+3
7=3+4
一共有14种情况,所以输出14
1 program p1171;
2 var n,ans,i:longint;
3
4 procedure init;
5 begin
6 assign(input,'input.txt');
7 reset(input);
8 assign(output,'output.txt');
9 rewrite(output);
10 readln(n);
11 close(input);
12 end;
13
14 procedure dfs(depth,x:longint);
15 var i,j:longint;
16 begin
17 if depth=n then
18 begin
19 inc(ans);
20 exit;
21 end;
22 if depth>n then
23 exit;
24 for i:=x to n-depth do
25 begin
26 inc(depth,i);
27 dfs(depth,i);
28 dec(depth,i);
29 end;
30 end;
31
32 begin
33 init;
34 ans:=0;
35 for i:=1 to n>>1 do
36 dfs(i,i);
37 writeln(ans);
38 close(output);
39 end.
分析:由于本人的搜索能力实在是太弱啦,RT,本程序思路来源于网络
1 program p1171;
2 var n,ans,i:longint;
3
4 procedure init;
5 begin
6 assign(input,'input.txt');
7 reset(input);
8 assign(output,'output.txt');
9 rewrite(output);
10 readln(n);
11 close(input);
12 end;
13
14 procedure dfs(depth,x:longint);
15 var i,j:longint;
16 begin
17 if depth=n then
18 begin
19 inc(ans);
20 exit;
21 end;
22 if depth>n then
23 exit;
24 for i:=x to n-depth do
25 begin
26 inc(depth,i);
27 dfs(depth,i);
28 dec(depth,i);
29 end;
30 end;
31
32 begin
33 init;
34 ans:=0;
35 for i:=1 to n>>1 do //优化
36 dfs(i,i);
37 writeln(ans);
38 close(output);
39 end.
浙公网安备 33010602011771号