第十三屆 ACM/CCPC 吉林省賽 E. Stick War

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 ≤ 10610^6) 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
在這裏插入圖片描述

題目大意:
  如上圖方式用木棍拼方塊,給你方塊的數量,求最少需要用多少根木棍?
 
分析:
  根據題意,我們很容易發現,只有將小方塊向大方塊的形狀上去拼,需要的木棍數量纔是最少的。
  那麼我們就需要知道,nn個小方塊能拼成多大的大方塊?答案是邊長爲[n][\sqrt{n}]的大方塊("[]“代表向下取整)。
 
思路:
  我們令t=[n]t= [\sqrt{n}],而:
  1. 邊長爲tt的大方塊,需要t×(t+1)×2t \times (t+1) \times 2根木棍拼成(自己證明)。
  2. 邊長爲tt的大方塊需要t×tt \times t個小方塊。
  注:這裏t=[n]t= [\sqrt{n}]的”[]"代表向下取整,也就是說,[n]×[n][\sqrt{n}] \times [\sqrt{n}]不一定等於nn。如:[5]=22×2=4[5]×[5]=4[\sqrt{5}] = 2, 2 \times 2 = 4,即[\sqrt{5}] \times [\sqrt{5}] = 4
  我們令v=nt×tv = n- t \times t,即nn個小方塊拼成邊長爲tt的大方塊後,還多出vv個小方塊。
  那麼多出來的小方塊怎麼算?我們不難看出,邊長爲tt的方塊向邊長爲t+1t+1的方塊方向上去拼,只需要填充兩條臨邊即可。如圖:
在這裏插入圖片描述
  根據上圖,我們不難看出,多出一(vv)個小方塊,就要多兩(v×2v \times 2)根木棍,且每條邊的起點處需要三根木棍。那麼規律就出來了:
  一共兩條邊,邊長爲tt,每條邊的第一個小方塊需要三根木棍,即第11個小方塊和第t+1t+1個小方塊各需要在v×2v \times 2的基礎上加一根木棍。所以多餘的小方塊需要木棍數量公式爲:v×2+(v0)+(v>t)v \times 2+(v \neq 0)+(v>t)  其中(v0)(v \neq 0)代表存在第一個小方塊;(v>t)(v > t)代表存在第t+1t+1個小方塊。所以,代碼如下:

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章