练习cf1345B. Card Constructions

题目如下
B. Card Constructions
time limit per test1 second
memory limit per test256 megabytes
A card pyramid of height 1 is constructed by resting two cards against each other. For ℎ>1, a card pyramid of height ℎ is constructed by placing a card pyramid of height ℎ−1 onto a base. A base consists of ℎ pyramids of height 1, and ℎ−1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
f02d3fa976f7a18ba4559a128e6b0410725828ca
You start with 𝑛 cards and build the tallest pyramid that you can. If there are some cards remaining, you build the tallest pyramid possible with the remaining cards. You repeat this process until it is impossible to build another pyramid. In the end, how many pyramids will you have constructed?

Input
Each test consists of multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤1000) — the number of test cases. Next 𝑡 lines contain descriptions of test cases.

Each test case contains a single integer 𝑛 (1≤𝑛≤109) — the number of cards.

It is guaranteed that the sum of 𝑛 over all test cases does not exceed 109.

Output
For each test case output a single integer — the number of pyramids you will have constructed in the end.

题目大意
如图一层一层堆金字塔,现有n根木棒,最多能堆几层。

题目分析
找规律可以得出,根数关于层数的方程为(3 * h * h + h) / 2,从第一层开始堆并计算需要的木棒总根数,并与当前具有的木棒根数进行比较,计算最多可以堆出的金字塔层数。

点击查看代码
#include <iostream>
using namespace std;

int main(){
    int t;
    cin >> t;
    while(t--){
        int n;
        cin >> n;
        int cnt = 0;
        while(n >= 2){
            int h = 1;
            int sum = (3 * h * h + h) / 2;
            while(sum <= n){
                h++;
                sum = (3 * h * h + h) / 2; 更新更高一层的金字塔所需木棒总数
            }
            h--; //不够进行下一层回退一层
            sum = (3 * h * h + h) / 2; //同时更新
            n -= sum; //跳出循环
            cnt++;
        }
        printf("%d\n", cnt);
    }
    return 0;
}
posted @ 2025-07-18 20:55  sirro1uta  阅读(10)  评论(0)    收藏  举报