题目描述
n hobbits are planning to spend the night at Frodo’s house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it’s not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.
Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?
Input
The only line contain three integers n, m and k (1 ≤ n ≤ m ≤ 109, 1 ≤ k ≤ n) — the number of hobbits, the number of pillows and the number of Frodo’s bed.
Output
Print single integer — the maximum number of pillows Frodo can have so that no one is hurt.
分析
先假定第k个位置的枕头的数量x个,那么k-1和k+1的位置为x-1个,以此向两边递推。
这样最后sum是最少的枕头数量,如果等于m正好,如果小于m,可以从两边向中间依次增加,这种情况一定满足条件
如果sum大于m,表示这种情况下最少的枕头数都比m大,显然m个枕头不够,所以这样就不满足条件了
代码
using namespace std;
long long n, m, k;
long long l, r, mid, ans;
int check(long long x)
{
long long sum=0;
if (k<=x)//因为依次递减1,所以x就是从1到x的堆数,k个堆如果小于等于k个堆
sum+=(x+(x-k+1))*k/2;//等差求和
else//如果多了,先算出从x到1的等差和,在其他堆都是1个枕头
sum+=(1+x)*x/2+k-x;
long long t=n-k+1;//第k堆算在内,向右的堆数
if (t<=x)//同上
sum+=(x+(x-t+1))*t/2;
else
sum+=(1+x)*x/2+t-x;
sum-=x;//sum加了两次第k堆的枕头数
if (sum<=m)
return 1;
else
return 0;
}
int main()
{
scanf("%lld%lld%lld", &n, &m, &k);
l=1, r=m;
while (l<=r){
mid=(l+r)/2;
if (check(mid)){
l=mid+1;
ans=mid;
}
else
r=mid-1;
}
printf("%lld", ans);
return 0;
}