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个位置堆枕头,但是要求相邻的位置的枕头数量只差不能超过1。
最直接的就是二分答案,然后判断当前的答案叠起来至少需要的被子数,如果小于等于m就是符合条件的情况。
这里计算至少需要的被子数的时候注意,有两种情况,一种情况就是类似
1
1111111111111这种,也就是头上的枕头应该至少是1的不是0.
另外一种情况就是:
1
111
11111很常规的这种。
和
1
111
111
111
这种。这两种其实是一种的。
总的来说就是根据二分的答案求阶梯和。
看看代码就懂了。
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
const int MAXN=1e5+7;
const int inf =1e9;
long long n,m,k,d1,d2;
long long check(long long mid)
{
long long sum=0;
//左边
if(mid-(k-1)<1)//如果头的位置的枕头数小于1
{
sum+=k-mid;
sum+=(1+mid)*mid/2;
}
if(mid-(k-1)>=1)//否则
{
sum+=(mid-(k-1)+mid)*k/2;
}
//右边
if(mid-(n-k)<1) //如果头的位置的枕头数小于1
{
sum+=n-k+1-mid;
sum+=(1+mid)*mid/2;
}
if(mid-(n-k)>=1)//否则
{
sum+=(mid-(n-k)+mid)*(n-k+1)/2;
}
if(sum-mid<=m)return 1;//mid算了两次
else return 0;
}
int main()
{
scanf("%I64d%I64d%I64d",&n,&m,&k);
long long ans=0;
long long l=1;
long long r=m;
while(r>=l)
{
long long mid=(l+r)/2;
if(check(mid))
{
ans=mid;
l=mid+1;
}
else r=mid-1;
}
printf("%I64d\n",ans);
return 0;
}