【CodeForces - 760B 】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 2Output
2Input
3 10 3Output
4Input
3 6 1Output
3Note
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個人(包括Frodo)在Frodo家里過夜,家里有n張床和m個枕頭,每個人都至少一張床和一個枕頭,但是每個人都想得到盡可能多的枕頭,但是如果有任何一個人的枕頭至少比他的鄰居少兩個,那么就會受傷。(對應(yīng)那句but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have.)Frodo睡在第k個位置(k<=n),問:在沒有人受傷的情況下,Frodo最多能得到多少個枕頭。
解題報告:
? ? 這題如果構(gòu)造的話,情況就太多了,,但是我們可以枚舉枕頭數(shù)啊,因為當(dāng)主人公的枕頭數(shù)定下來之后,就很好得到每一次的最優(yōu)構(gòu)造了,就是一個簡單的數(shù)學(xué)求和公式了。代碼寫的很冗長,但是思路很簡單。我只是分了情況(在兩邊和不在兩邊)。
AC代碼:
#include<bits/stdc++.h> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; ll n,m,k; bool ok1(ll x) {ll res = 0;if(n < x) res = ((x-n+1) + x) * n / 2;else res = (1+x)*x/2;return res <= m; } bool ok2(ll x) {ll res1,res2;if(k < x) res1 = ((x-k+1)+x)*k/2;else res1 = (1+x)*x/2;if(n-k+1 < x) res2 = ((x-(n-k+1)+1)+x)*(n-k+1)/2;else res2 = (1+x)*x/2;return res1 + res2 - x <= m; } int main() {cin>>n>>m>>k;//n人 m枕頭 在第k個 if(n == m) {printf("1");return 0;}m=m-n;//默認每個人有一個ll l = 0,r = m;ll ans = 0;ll mid = (l+r)>>1;if(k == 1 || k == n) {k=1;while(l <= r) {mid = (l+r)>>1;if(ok1(mid)) {ans=mid;l=mid+1;}else r=mid-1;}}else {while(l<=r) {mid = (l+r)>>1;if(ok2(mid)) {ans = mid;l=mid+1;}else r=mid-1;}}printf("%lld\n",ans+1);return 0 ;}總結(jié):
? 注意一個細節(jié)就是ok2函數(shù)中構(gòu)造的時候,中間那條邊會被計算兩次,舉個例子
? 樣例:
? ?4 8 2
? ?應(yīng)該輸出3,結(jié)果輸出了2。就是因為,x=3的時候,本來用不到m塊枕頭,但是你重復(fù)計算了一次,所以就多算了枕頭數(shù),所以就返回了false了、、、
總結(jié)
以上是生活随笔為你收集整理的【CodeForces - 760B 】Frodo and pillows (二分题意,注意细节)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡最大透支额度是多少 提额技巧帮你透
- 下一篇: 关于C++里面使用set_union,s