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 10

大意:找到r圈,i为1到r圈,依次为k的i次方的蜡烛个数,找到这个r和k。

思路:通过提前的计算得出,r最大只能为40,所以可以通过枚举进行,然后里面的k的选择出来的方法是通过二分法进行的。这里要注意的是为了避免数据溢出的操作!!;

小技巧:关于相乘可能导致的数据溢出,提前判断的方法是通过相处来判断,以后要成一个习惯即通过k的n次方这种,一开始先设立的为1,然后之后进行先乘在求和的操作,而不是设立一开始的k,然后先求和再乘,后者不能进行判断是否在一开始求和前有溢出的可能(尽量在求和前判断,而非求和后判断);

代码:

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值