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?
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.
Print single integer — the maximum number of pillows Frodo can have so that no one is hurt.
4 6 2
2
3 10 3
4
3 6 1
3
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个霍比特人排成一行准备睡觉,他们有n张床和m个枕头,弗拉多作为主人要给这些人分枕头。每个霍比特人都希望自己有尽可能多的枕头,而每个霍比特人只要比跟他相邻的人少一个以上的枕头(不包括一个),他就会受到伤害,问弗拉多在不会伤害任意一个人的情况下能获得最多多少枕头。
思路:一看就是一个贪心题,那么在如此之大的数据范围下如何确定弗拉多该有多少枕头呢?果断选择二分。剩下就只需要一个等差数列公式来求枕头总和了。
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<cstdlib>
#include<ctime>
using namespace std;
const int MAXN=1e9+7;
long long n,m,k;
int main()
{
scanf("%I64d%I64d%I64d",&n,&m,&k);
long long l=1,r=MAXN,mid,ans=0,tot;
if (n==k && k==1)
{
cout<<m;
return 0;
}
while (l<=r)
{
long long x=0,y=0;
tot=0;
mid=(l+r)>>1;
if (k!=1)
{
if (k>mid)
{
x=(1+mid)*(mid)/2+(k-mid);
}
else
{
x=(mid+(mid-k+1))*k/2;
}
}
if (k!=n)
{
if (mid<=(n-k+1))
{
y=(mid+1)*mid/2+(n-k+1-mid);
}
else
{
y=(mid+(mid-n+k))*(n-k+1)/2;
}
}
tot=x+y;
if (k!=1 && k!=n)
{
tot-=mid;
}
if (tot<=m)
{
ans=mid;
l=mid+1;
}
else
{
r=mid-1;
}
}
cout<<ans;
return 0;
}