while (l < r)
{
int mid = l + r >> 1; //(l+r)/2
if (check(mid)) r = mid; // check()判断mid是否满足性质
else l = mid + 1;
}
while (l < r)
{
int mid = l + r + 1 >> 1;
//(l+r+1)/2,往右找答案要加1
if (check(mid)) l = mid;
else r = mid - 1;
}
分巧克力
https://www.luogu.com.cn/problem/P8647
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int h[maxn];
int w[maxn];
int n,k;
bool check(int ans)
{int sum=0;
for(int i=0;i<n;i++)
{
sum+=(h[i]/ans)*(w[i]/ans);
}
if(sum<k)return false;
else
return true;
}
int bs(int l,int r)
{
while(l<r)
{ int mid=(l+r+1)>>1;//写在while外面导致tle
if(check(mid))
l=mid;
else
r=mid-1;
}
return l;
}
int main()
{
cin>>n>>k;
for(int i=0;i<n;i++)
{
cin>>h[i]>>w[i];
}
cout<<bs(1,maxn);
}
杨辉三角(二分答案行+数学性质)
include
typedef long long LL;
const LL INF=1e9;
LL n;
LL C(LL a,LL b){
LL res=1;
for(LL i=a,j=1;j<=b;i--,j++){
res=resi/j;
if(res>n) // fixed
return res;
}
return res;
}
int main(){
scanf("%lld",&n);
// 只需遍历 16 行
if(n==1){
printf("1");
return 0;
}
for(int i=16;i>=0;i--){
LL l=2i,r=INF,mid,lim;
while(l<=r){
mid=(l+r)>>1,lim=C(mid,i);
//第mid行,第i条对角线
if(lim==n){
printf("%lld",(mid+1)*mid/2+i+1);
//因为从0行开始,但是因为在计算元素位置时,实际索引从 1 开始
return 0;
}else if(lim<n)
l=mid+1;
else{
r=mid-1;
}
}
}
return 0;
}
#include<cstdio>
typedef long long LL;
const LL INF=1e9;
LL n;
LL C(LL a,LL b){
LL res=1;
for(LL i=a,j=1;j<=b;i--,j++){
res=res*i/j;
if(res>n) // fixed
return res;
}
return res;
}
int main(){
scanf("%lld",&n);
// 只需遍历 16 行
if(n==1){
printf("1");
return 0;
}
for(int i=16;i>=0;i--){
LL l=2*i,r=INF,mid,lim;
while(l<=r){
mid=(l+r)>>1,lim=C(mid,i);
//第mid行,第i条对角线
if(lim==n){
printf("%lld",(mid+1)*mid/2+i+1);
//因为从0行开始,但是因为在计算元素位置时,实际索引从 1 开始
return 0;
}else if(lim<n)
l=mid+1;
else{
r=mid-1;
}
}
}
return 0;
}
标签:二分,return,int,res,LL,mid,第二周,lim,9.7
From: https://www.cnblogs.com/hoshino-/p/18402115