• 搭建金字塔


    题目大意:

    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;
    
    

    心得:
    通过之前看过的阶乘计算的方法找到了思路,这个题目算简单题,要注意定义中间变量,这样好理解一些。判断的条件也要仔细考虑,输出时也要学会做处理。第二天的比赛状态比第一天差些,还是要好好调整!

    
    
     
     
     
    ------------------------ 没有谁的人生不是斩棘前行 ---------------------------------------- JM
  • 相关阅读:
    小程序与普通网页的区别
    小程序的结构
    Vuex四个map的方法使用
    Vuex的基本使用
    getters的使用
    nodeffi从入门到放弃(安装篇)
    nodejs如何调用c语言 (FFI)
    解决 nodegyp 错误问题
    NodeJS 调用C++(Nodeffi)
    Electron9.x +vue+ffinapi 调用Dll动态链接库
  • 原文地址:https://www.cnblogs.com/Lynn0814/p/4652571.html
Copyright © 2020-2023  润新知