题目描述
Farmer John 欠了 Bessie N 加仑牛奶(1≤N≤10^12)。他必须在 K 天内将牛奶给 Bessie。但是,他不想将牛奶太早拿出手。另一方面,他不得不在还债上有所进展,所以他必须每天给 Bessie 至少 M 加仑牛奶(1≤M≤10^12)。
以下是 Farmer John 决定偿还 Bessie 的方式。首先他选择一个正整数 X。然后他每天都重复以下过程:
- 假设 Farmer John 已经给了 Bessie G 加仑,计算 (N−G)/X 向下取整。令这个数为 Y。
- 如果 Y 小于 M,令 Y 等于 M。
- 给 Bessie Y 加仑牛奶。
求 X 的最大值,使得 Farmer John 按照上述过程能够在 K 天后给 Bessie 至少 N 加仑牛奶 (1≤K≤10^12)。
输入
输入仅有一行,包含三个空格分隔的正整数 N、K 和 M,满足 K⋅M<N。
注意这个问题涉及到的整数规模需要使用 64 位整数类型(例如,C/C++ 中的“long long”)。
输出
输出最大的正整数 X,使得按照上述过程 Farmer John 会给 Bessie 至少 N 加仑牛奶。
样例输入
10 3 3
样例输出
2
数据范围限制
测试点 1-3 满足 K≤10^5。
测试点 4-10 没有额外限制。
提示
在这个测试用例中,当 X=2 时 Farmer John 第一天给 Bessie 5 加仑,后两天每天给 Bessie M=3 加仑。
思路:
根据题目K⋅M<N,可知道x<N,x的范围很大,所以第一时间想到的是log(n)的二分。
想到二分后,还要想,如何判断x是否成立,常规想法是O(K)的算法,可1≤K≤10^12,明显超时,那又得换方法了。
Y=(N−G)/X 向下取整,(N−G)会越来越小,那么也Y一定会越来越小,如果Y有一天<=M,那Y以后都等于M,那Y实际最后要交(剩余天数 * M)+ G 的牛奶。
再想Y没有小于M的时候,它可能交a天Y加仑牛奶,那a怎么求呢?我们知道(g-(a-1)y)/x>=y可以推出g/y-a+1>=x也就是g/y-x+1>=a ; (g-a * y)/x<y可推出g/y-x<a。结合两式可发现a=g/y-x+1。
核心算法:
//o为x
while(s>0){
long long y=(n-g)/o;
if(y<=m){
g+=s*m;
s=0;
break;
}
else{
long long a=(n-g)/y-o+1;
if(a<=s){
g+=a*y;
s-=a;
}
else{
g+=s*y;
s=0;
}
}
}
return g;