ACM/CCPC 歷屆真題 題解目錄
Problem E. Stick War
Time Limit: 1000ms Memory Limit: 512MB
Description
The Stick Kingdom will start a war to the Hammer Kingdom! The power of the stick army is the number of 1 ∗ 1 grids made up of sticks. The king of Stick Kingdom would give you the grids he needed, and you should tell him the minimum number of sticks he needed.
Note: it’s very difficult for sticks to stand up, so the grids must be made on a 2-D plane.
Input
First line contains an integer T (1 ≤ T ≤ 10v) represents the number of test cases.
For each test case:
The first line contains an integer n (1 ≤ n ≤ ) represents the number of grids the king needed.
Output
For each test case, output a line contains an integer represents the minimum number of sticks the king needed.
Sample
Input
4
1
2
3
4
Output
4
7
10
12
Hint
題目大意:
如上圖方式用木棍拼方塊,給你方塊的數量,求最少需要用多少根木棍?
分析:
根據題意,我們很容易發現,只有將小方塊向大方塊的形狀上去拼,需要的木棍數量纔是最少的。
那麼我們就需要知道,個小方塊能拼成多大的大方塊?答案是邊長爲的大方塊("[]“代表向下取整)。
思路:
我們令,而:
1. 邊長爲的大方塊,需要根木棍拼成(自己證明)。
2. 邊長爲的大方塊需要個小方塊。
注:這裏的”[]"代表向下取整,也就是說,不一定等於。如:。
我們令,即個小方塊拼成邊長爲的大方塊後,還多出個小方塊。
那麼多出來的小方塊怎麼算?我們不難看出,邊長爲的方塊向邊長爲的方塊方向上去拼,只需要填充兩條臨邊即可。如圖:
根據上圖,我們不難看出,多出一()個小方塊,就要多兩()根木棍,且每條邊的起點處需要三根木棍。那麼規律就出來了:
一共兩條邊,邊長爲,每條邊的第一個小方塊需要三根木棍,即第個小方塊和第個小方塊各需要在的基礎上加一根木棍。所以多餘的小方塊需要木棍數量公式爲: 其中代表存在第一個小方塊;代表存在第個小方塊。所以,代碼如下:
#include <iostream>
#include <cmath>
using namespace std;
int t, n;
int main()
{
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
int t = sqrt(n); //大方塊邊長t
int v = n - t*t; //多v個小方塊
int ans = t * (t+1) * 2; //大方塊需要的木棍數量
ans += v * 2 + (v != 0) + (v > t); //加上v個小方塊需要的木棍數量
printf("%d\n", ans);
}
return 0;
}