zoukankan      html  css  js  c++  java
  • Javabeans(递推)

    Javabeans

    Time Limit: 2 Seconds      Memory Limit: 65536 KB

    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 }
  • 相关阅读:
    经典面试题(二)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯
    ctype.h库函数
    结构体大小与内存对齐问题
    整数v,从高位到低位,取c位数,得到最大数 (其中:v>=10^c)
    32位与64 位下各类型长度对比
    C++容器类
    笔试题 相对位置不变的正负数排序
    composer 下载安装
    nginx 多进程 + io多路复用 实现高并发
    go 成长路上的坑(1)
  • 原文地址:https://www.cnblogs.com/cszlg/p/2932459.html
Copyright © 2011-2022 走看看