#639 (Div. 2)B. Card Constructions

题目描述:

A card pyramid of height 1 is constructed by resting two cards against each other. For h>1, a card pyramid of height h is constructed by placing a card pyramid of height h−1 onto a base. A base consists of h pyramids of height 1, and h−1 cards on top. For example, card pyramids of heights 1, 2, and 3 look as follows:
在这里插入图片描述
You start with n 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 t (1≤t≤1000) — the number of test cases. Next t lines contain descriptions of test cases.
Each test case contains a single integer n (1≤n≤109) — the number of cards.
It is guaranteed that the sum of n 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.

Example

input
5
3
14
15
24
1
output
1
2
1
3
0

Note

In the first test, you construct a pyramid of height 1 with 2 cards. There is 1 card remaining, which is not enough to build a pyramid.
In the second test, you build two pyramids, each of height 2, with no cards remaining.
In the third test, you build one pyramid of height 3, with no cards remaining.
In the fourth test, you build one pyramid of height 3 with 9 cards remaining. Then you build a pyramid of height 2 with 2 cards remaining. Then you build a final pyramid of height 1 with no cards remaining.
In the fifth test, one card is not enough to build any pyramids.

题目大意:

有如上图各种层数的纸牌塔,你有n张纸牌,并且你每次只能搭你当前可以搭的最大层数的塔。问你可以用这n张牌搭多少塔。

题目分析:

因为每层塔需要的卡牌数是固定的,也有规律,因此我们可以先预处理出各层塔的高度。然后再算出n张牌能搭多少塔即可。
一层:2
两层:2+2+3=7
三层:7+2+6=15
四层:15+2+9=26
我们可以看出:第i层塔需要的纸牌即为:h[i]=h[i-1]+2+(i-1)*3.
然后我们可以遍历h找到小于等于n的最大值,然后不断的让n-=h[i],看看能减几次即可。

代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <vector>
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
int const N=1e5+5;
int h[N];
int main()
{
	int k=1;           //预处理出h数组
	h[k]=2;
	while(2e9>h[k])    //n<=1e9,h要多往后求一些
	{
		k++;
		h[k]=h[k-1]+2+(k-1)*3;
	}
	int t;
	cin>>t;
	while(t--)
	{
		int n;
		cin>>n;
		int i;
		for(i=1;i<=k;i++)     //找到小于等于n的最大值
		if(h[i]>n) {i--; break;}
		
		int cnt=0;
		while(n>1&&i>0)      //统计能相减几次
		{
			while(i>0&&n>=h[i]) n-=h[i],cnt++;
			while(i>0&&n<h[i]) i--;
		}
		cout<<cnt<<endl;
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/li_wen_zhuo/article/details/105964474
今日推荐