题目链接:Problem - 760B - Codeforces
题意:给n个床位,m个枕头。主人睡在第k个床。每个人都至少有一张床和一个枕头。如果有任何一个人,他旁边的两个人的都比他多了一个枕头,那么他就会受伤。问:在没有人受伤的情况下,主人最多能得到多少个枕头。
思路:
因为n和m都比较大,所以用二分,不然会超时。由题意我们可以发现,每个人拥有的枕头数是以主人为中心分别向两边递减的等差数列(枕头可以不必用完),因此我们可以通过自定义函数判断mid是否满足要求,只要所有要用到的枕头数小于m就可以了。
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
int n, m, k, ans;
bool checl(int x)
{
int s1 = 0,s2 = 0;
if (x >= k)
{
s1 = (x * 2 - k + 1) * k / 2;//利用(a1+an)*n/2公式
}
else
{
s1 = (1 + x) * x / 2 + k - x;//利用a1*n+n*(n-1)*d/2公式
}
int k1 = n - k + 1;
if (x >= k1)
{
s2 = (x * 2 - k1 + 1) * (k1) / 2;
}
else
{
s2 = (1 + x) * x / 2 + k1 - x;
}
if (s1 + s2 - x <= m)//总数加起来小于m说明符合。
{
return 1;
}
else
return 0;
}
int main()
{
cin >> n >> m >> k;
int l = 1, r = m;
while (l <= r)
{
int mid = (l + r) / 2;
if (checl(mid))//利用函数判断mid是否符合题意
{
ans = mid;
l = mid + 1;
}
else
r = mid - 1;
}
cout << ans;
return 0;
}