C. Increase and Copy
Description
Initially, you have the array a consisting of one element 1 (a=[1]).
In one move, you can do one of the following things:
Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase ai by one);
Append the copy of some (single) element of a to the end of the array (choose some i from 1 to the current length of a and append ai to the end of the array).
For example, consider the sequence of five moves:
You take the first element a1, append its copy to the end of the array and get a=[1,1].
You take the first element a1, increase it by 1 and get a=[2,1].
You take the second element a2, append its copy to the end of the array and get a=[2,1,1].
You take the first element a1, append its copy to the end of the array and get a=[2,1,1,2].
You take the fourth element a4, increase it by 1 and get a=[2,1,1,3].
Your task is to find the minimum number of moves required to obtain the array with the sum at least n.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1≤t≤1000) — the number of test cases. Then t test cases follow.
The only line of the test case contains one integer n (1≤n≤109) — the lower bound on the sum of the array.
Output
For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least n.
Example
input
5
1
5
42
1337
1000000000
output
0
3
11
72
63244
题意: 给定一个初始数组 a = [ 1 ] a = [1] a=[1],要求通过最少的操作使得数组a的和的值达到给定的值。对数组a的操作如下:
- 可以复制a中的任意一个元素放到末尾,如:
- 最开始时 a = [ 1 ] a=[1] a=[1],通过复制a中唯一的元素,把它放到末尾,这时a就变成了 [ 1 , 1 ] [1,1] [1,1]。
- 将a中任意一个元素加1,如:初始时 a = [ 1 ] a =[1] a=[1],通过对a中唯一的元素加一,这时a就变成了 [ 2 ] [2] [2]。
题解: 先自增到某个数x,然后复制这个x若干次直到超过n。所以只需要枚举 [ 1 , n ] [1,\sqrt n] [1,n]之间的因数,枚举x作比较即可。
c++ AC 代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t, n;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
int ans = 1e9 + 11;
int t = sqrt(n) - 1;
for (int i = 0; i <= t; i++)
{
int now = i + 1; // 先自增
int num = (n - 1) / now; // 再复制
ans = min(ans, num + i);
}
printf("%d\n", ans);
}
// system("pause");
return 0;
}