SPOJ - PHT【二分+预处理】

Pigeon SSNA want to build a tower with some wood walls. Let's describe the tower they want to make:

  1. A Tower can consist of different number of level.
  2. If a tower contain levels then 1st level must contain  holes , 2nd level L-1 , 3rd level L-2 ….. L level contain 1 hole .
  3. Each room contain 3 wood walls.

See the picture below:

3 Level Tower 4 Level tower

Now pigeon SSNA has n wood walls. What is maximum number of level he can made.

Input

Input starts with an integer T (≤ 100000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 1012)

Output

For each case of input you have to print the case number and expected answer.

Sample Input

Output for Sample Input

2
15
24
Case 1: 3
Case 2: 4

题目大意;

给你n个木棒,问你最多可以搭出来几层,按照题干图示方式去搭。


思路(连续考三天试,好烦啊T T ):


1、不难发现,第一层需要3个木棒,第二层需要5个木棒,第三层需要7个木棒..................依次类推,对应我们N有一个范围,那么我们预处理出sum【i】<=1e12以内所有的数据,接下来对应每个询问,进行查询。


2、预处理过程发现数组大小为1000000.那么对应我们如果O(n)去查询的话,因为T比较大,所以我们O(nT)是会超时的。

考虑到sum【i】数组中的数据是严格递增的,具有单调性,那么我们考虑使用二分来优化整个查询,总时间复杂度O(Tlogn).



Ac代码:


#include
#include
using namespace std;
#define ll long long int
ll a[45454005];
ll sum[45454005];
void init()
{
    sum[1]=3;
    a[1]=3;
    ll tmp=2;
    for(int i=2;;i++)
    {
        a[i]=tmp+a[i-1];
        sum[i]=sum[i-1]+a[i];
        if(sum[i]>1000000000000)
        {
            break;
        }
    }
}
int main()
{
    int kase=0;
    init();
    int t;
    scanf("%d",&t);
    while(t--)
    {
        ll n;
        scanf("%lld",&n);
        int l=0;
        int r=1000000;
        int ans=-1;
        while(r-l>=0)
        {
            int mid=(l+r)/2;
            if(sum[mid]>=n)
            {
                if(sum[mid]==n)
                ans=mid;
                else ans=mid-1;
                r=mid-1;
            }
            else
            {
                l=mid+1;
            }
        }
        printf("Case %d: ",++kase);
        printf("%d\n",ans);
    }
}









你可能感兴趣的:(二分查找)