比赛--建金字塔问题--解题报告

建金字塔问题

题目大意:

Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... + (i - 1) + i cubes.

Vanya wants to know what is the maximum height of the pyramid that he can make using the given cubes。

要求:

Input

The first line contains integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya.

Output

Print the maximum possible height of the pyramid in the single line.

样例输入:

Input

1

Output

1

Input

25

Output

4

提示:

Illustration to the second sample:

 

题目分析:
题目主要运用累加法。  每层及以上层的所有立方体都相加。要注意比较每层建完后所剩的立方体数与下一层所需的立方体数,如果不够建下一层则金字塔的建立结束。
使用for循环完成累加操作,输出的是层数(i-1)而不是i。
程序代码:
 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 
 5 int n[10000];
 6 
 7 int main()
 8 {
 9     int n,i=0,m=0,a=0,b;
10     scanf("%d",&n);        //输入立方体总数
11     for(i;a<=n;i++)        //for 循环求出层数,比较剩余立方体数与下一层所需立方体数
12     {
13         m+=i;
14         a+=m;    
15         b=i-1;
16     }
17     cout<<b<<endl;         //输出层数
18     return 0;
19 }

心得:
这也是一道比较简单的题目,主要用到累加法 。要注意输出的是以建的层数,但做完for 循环后i++,比以建的多一层,所以输出的是i-1,做题时这点需要注意。做题时还是要仔细思考,想清题目所要输出的结果。

 

 

posted @ 2015-07-17 11:28  tmj  阅读(267)  评论(0编辑  收藏  举报