题目大意:
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.
Sample Input
Input
1
Output
1
Input
25
Output
4
思路分析:
整体方向是所拥有的木块数N与能建层数需要的木块数sum的比较,即每建一层,目前所用的sum总数跟N比较,
如果N>sum那么久继续建直到N<=sum停止计算。
用两层循环计算总数。内层循环用来计算当前最底层需要的木块数,外层循环sum加上内层循环得数就是当前所需木块总数,
每建完一层就做比较。最后输出i时要做一些处理,具体见代码。
源代码:
1 #include<iostream> 2 using namespace std; 3 int main() 4 { 5 int n; 6 while (cin >> n) //输入多组案例,以0结束 7 { 8 int sum = 0, m = 0; 9 for (int i = 1;; i++) 10 { 11 12 sum += m; //目前所需要的木块总数 13 14 if (n > sum) 15 { 16 int k = 0; //定义中间变量 17 for (int j = 0; j <= i; j++) 18 { 19 20 k += j; //计算当前层所需的木块数 21 m = k; 22 } 23 } 24 if (n - sum == 0) 25 { 26 cout << i - 1 << endl; //n==sum时输出i-1,因为开始 27 break; //时第一层没有用木块也算进去了 28 } 29 if (n<sum) 30 { 31 cout << i - 2 << endl; //小于时除了减去开始多算的一 32 break; //层,还要算借来木块多算的一层。 33 } 34 } 35 } 36 //system("pause"); 37 return 0;
心得:
通过之前看过的阶乘计算的方法找到了思路,这个题目算简单题,要注意定义中间变量,这样好理解一些。判断的条件也要仔细考虑,输出时也要学会做处理。第二天的比赛状态比第一天差些,还是要好好调整!