Frodo and pillows

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.

Examples
Input
4 6 2
Output
2
Input
3 10 3
Output
4
Input
3 6 1
Output
3
Note
In the first example Frodo can have at most two pillows. In this case, he can give two pillows to the hobbit on the first bed, and one pillow to each of the hobbits on the third and the fourth beds.

In the second example Frodo can take at most four pillows, giving three pillows to each of the others.

In the third example Frodo can take three pillows, giving two pillows to the hobbit in the middle and one pillow to the hobbit on the third bed.

题目大意:
输入n个人,共有m个枕头,其中Frodo在第K个位置,需要输出的是他最多可以有多少个枕头。要求是相邻两个人的枕头差值不能超过1。
解题思路:
本题采用二分的思想。二分枕头数给Frodo,然后从k向左加和,再向右加和,相加和m比较,看是否符合条件。大致的思路就是这样,不过其中有一些小细节,可以看代码自行体会。(里面的对左右侧枕头求和,都是用的等差数列求和公式)
AC代码:

#include<bits/stdc++.h>
using namespace std;
long long n,m,k,l,r,mid,ans;
long long int check(long long x)
{
	long long sum=0;
	if(k<=x)//如果左边位置小与枕头数,则用等差数列来求和 
	    sum+=(x+(x-k+1))*k/2;
    else // 如果左边位置大于枕头数,那就先算等差数列,其余的数量都是1 
	    sum+=(1+x)*x/2+k-x;        
	long long t=n-k+1;
	if(t<=x)//右侧与左边道理相同 
	    sum+=(x+(x-t+1))*t/2;
	else
	    sum+=(1+x)*x/2+t-x;
	sum=sum-x;//因为左边的时候算了一次x,右边又算了一次
	if(sum<=m)
	    return 1;//sum小与m,说明此种情况满足
	else
	    return 0; 
}
int main()
{
	cin >> 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值