题目很简单,就是我们在写二分的时候,会遇到这样的情况:
mid =left +(right-left)/2;
if (nums == k)return mid;if (nums>k)left = mid;if (nums<k)right = mid-1;
若我们debug会发现其可能会一致卡在left = mid,例如(0,1),那么就会一直循环
其实可以改为
mid =left +(right-left)/2+1;
那么就可以了。
#include <cstdio>
#include <cmath>
const int N =1e3+10;
int n,k;
int q[N];int binary_search(int left,int right){int mid;int nums=0;while (left<right){nums = 0;mid =left +(right-left)/2+1;for (int i = 0;i<n;i++){nums+=q[i]/mid;}if (nums == k)return mid;if (nums>k)left = mid;if (nums<k)right = mid-1;printf("%d %d\n",left,right);}return left;
}
int main(){scanf("%d%d",&n,&k);int max_=0;for (int i=0;i<n;i++){scanf("%d",&q[i]);if (q[i]>max_)max_ = q[i];}printf("%d",binary_search(0,max_));return 0;}