Javabeans(递推)
Javabeans are delicious. Javaman likes to eat javabeans very much.
Javaman has n boxes of javabeans. There are exactly i javabeans in the i-th box (i = 1, 2, 3,...n). Everyday Javaman chooses an integer x. He also chooses several boxes where the numbers of javabeans are all at least x. Then he eats x javabeans in each box he has just chosen. Javaman wants to eat all the javabeans up as soon as possible. So how many days it costs for him to eat all the javabeans?
Input
There are multiple test cases. The first line of input is an integer T ≈ 100 indicating the number of test cases.
Each test case is a line of a positive integer 0 < n < 231.
Output
For each test case output the result in a single line.
Sample Input
4 1 2 3 4
Sample Output
1 2 2 3
这题的关键是x怎么选取,最优解取x = [n/2].
用f(k)表示n=k时所需的天数。
当 n=2k+1, k为非负整数,原序列为<1, 2, ..., k+1, ..., 2k+1>.中间的一个数是k+1,则先取 x=k+1,原序列变为<1, 2, ..., k , 0, 1, 2..., k>.可以发现,两边对称,于是 f(2k+1)=1+f(k).即f(n)=1+f([n/2]).
当n=2k, k为非负整数,原序列为<1, 2, ..., k, k + 1, ..., 2k>.取x=n/2=k,原序列变为<1, 2, ..., k-1, 0 , 1, 2,.., k>.两边对称,于是f(2k)=1+f(k).也满足f(n)=1+f([n/2]).
于是得到递推公式:f(n)=1+f([n/2]).
那么为什么要取x = [n/2]? 因为这能使得原序列“最快”地被分割为尽可能小的序列。不断取x = [n/2]就将原序列不断地二分。如果取x=[n/a].a>2,则分割成的序列中总有长度大于[n/2]的。
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <cmath> 5 #include <cstring> 6 #include <algorithm> 7 #include <map> 8 #include <vector> 9 #include <set> 10 #include <queue> 11 #include <stack> 12 #define LL long long 13 #define MAXI 2147483647 14 #define MAXL 9223372036854775807 15 #define eps (1e-8) 16 #define dg(i) cout << "*" << i << endl; 17 18 using namespace std; 19 20 int Solve(LL n) 21 { 22 if(n == 1) return 1; 23 return 1 + Solve(n / 2); 24 } 25 26 int main() 27 { 28 LL n; //尽管n是32位整型,但为免运算过程中发生溢出,仍设为64位 29 int t; 30 cin >> t; 31 while(t--) 32 { 33 cin >> n; 34 cout << Solve(n) << endl; 35 } 36 return 0; 37 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 数据库服务器 SQL Server 版本升级公告
· 程序员常用高效实用工具推荐,办公效率提升利器!
· C#/.NET/.NET Core技术前沿周刊 | 第 23 期(2025年1.20-1.26)