One curious child has a set of N little bricks. From these bricks he builds different staircases. Staircase consists of steps of different sizes in a strictly descending order. It is not allowed for staircase to have steps equal sizes. Every staircase consists of at least two steps and each step contains at least one brick. Picture gives examples of staircase for N=11 and N=5:
图片看不清楚?请点击这里查看原图(大图)。
Your task is to write a program that reads from input numbers N and writes to output numbers Q - amount of different staircases that can be built from exactly N bricks.
Input
Numbers N, one on each line. You can assume N is between 3 and 500, both inclusive. A number 0 indicates the end of input.
Output
Numbers Q, one on each line.
Sample Input
3
5
0
Sample Output
1
2
效率较低的递归法:
递归
1#include <stdio.h>
2#include <stdlib.h>
3
4int solve(int num, int step);
5int n;
6
7int main()
8{
9 while(scanf("%d", &n) && n!=0){
10 printf("%dn", solve(n, 1));
11 }
12
13 return 0;
14}
15
16int solve(int num, int step)
17{
18 int p, q;
19
20 if(num == step){
21 return 1;
22 }
23 else{
24 q = 0;
25 for(int i=step; i<=(num-1)/2; i++){
26 q += solve(num-i, i+1);
27 }
28 if(num > step && num != n)
29 q ++;
30 return q;
31 }
32}
33
AC了的:DP
DP
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int main()
6{
7 int i, j, k, n;
8 double num[501][501];
9
10 memset(num, 0x00, sizeof(num));
11 for(i=1; i<=500; i++)
12 num[i][i] = 1;
13 for(i=3; i<=500; i++)
14 for(j=1; j<=(i-1)/2; j++){
15 for(k=j+1; k<=(i-1)/2; k++)
16 num[j][i] += num[k][i-j];
17 num[j][i] += num[i-j][i-j];
18 }
19 for(i=3; i<=500; i++)
20 for(j=1; j<=(i-1)/2; j++)
21 num[0][i] += num[j][i];
22
23 while(scanf("%d", &n)==1 && n!=0){
24 printf("%0.0fn", num[0][n]);
25 }
26
27 return 0;
28}
版权与免责声明
1、本站所发布的文章仅供技术交流参考,本站不主张将其做为决策的依据,浏览者可自愿选择采信与否,本站不对因采信这些信息所产生的任何问题负责。
2、本站部分文章来源于网络,其版权为原权利人所有。由于来源之故,有的文章未能获得作者姓名,署“未知”或“佚名”。对于这些文章,有知悉作者姓名的请告知本站,以便及时署名。如果作者要求删除,我们将予以删除。除此之外本站不再承担其它责任。
3、本站部分文章来源于本站原创,本站拥有所有权利。
4、如对本站发布的信息有异议,请联系我们,经本站确认后,将在三个工作日内做出修改或删除处理。
请参阅权责声明!