题目: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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。