2017級寒假講座二分三分訓練題 F - Yukari's Birthday (二分法的用法之一)

題目:F - Yukari's Birthday
Today is Yukari's n-th birthday. Ran and Chen hold a celebration party for her. Now comes the most important part, birthday cake! But it's a big challenge for them to place n candles on the top of the cake. As Yukari has lived for such a long long time, though she herself insists that she is a 17-year-old girl.
To make the birthday cake look more beautiful, Ran and Chen decide to place them like r ≥ 1 concentric circles. They place k i candles equidistantly on the i-th circle, where k ≥ 2, 1 ≤ i ≤ r. And it's optional to place at most one candle at the center of the cake. In case that there are a lot of different pairs of r and k satisfying these restrictions, they want to minimize r × k. If there is still a tie, minimize r.
Input
There are about 10,000 test cases. Process to the end of file.
Each test consists of only an integer 18 ≤ n ≤ 10 12.
Output
For each test case, output r and k.
Sample Input
18
111
1111
Sample Output
1 17
2 10
3 10ide

大意:找到r圈,i爲1到r圈,依次爲k的i次方的蠟燭個數,找到這個r和k。ui

思路:經過提早的計算得出,r最大隻能爲40,因此能夠經過枚舉進行,而後裏面的k的選擇出來的方法是經過二分法進行的。這裏要注意的是爲了不數據溢出的操做!!;rest

小技巧:關於相乘可能致使的數據溢出,提早判斷的方法是經過相處來判斷,之後要成一個習慣即經過k的n次方這種,一開始先設立的爲1,而後以後進行先乘在求和的操做,而不是設立一開始的k,而後先求和再乘,後者不能進行判斷是否在一開始求和前有溢出的可能(儘可能在求和前判斷,而非求和後判斷);code

代碼:ci

#include<stdio.h>

int main()
{
    long long r,k,i,j,n;
    while(scanf("%lld",&n)!=EOF){
            long long left,right,mid,mids,mins=n-1,min_r=1,min_k=n-1;
            long long  sum;
            for(r=1;r<=40;r++){
                left=1;right=n;
                while(right>=left){
                    sum=0;
                    mid=(right+left)/2;
                    mids=1;//對於這個有很大的可能出現溢出的問題的時,儘可能一開始先是1,畢竟有可能一上來就未必知足相加的條件
                    for(i=1;i<=r;i++)
                    {
                        if(n/mids<mid)
                        {
                            sum=n+1;
                            break;}
                        mids*=mid;
                        sum+=mids;
                        if(sum>n)
                            break;

                    }
                   // printf("%lld\n",sum);
                    if(sum==n-1||sum==n){
                        if(mins>r*mid)
                        {mins=r*mid;min_r=r;min_k=mid;}
                    }
                    if(sum>n)
                        right=mid-1;
                    else
                        left=mid+1;
              //  printf("%lld\n",min_k);
              //  printf("%lld %lld\n",right,left);
                }
            }
            printf("%lld %lld\n",min_r,min_k);
    }
    return 0;
}
相關文章
相關標籤/搜索