典型的二分题目,求最大长度。
二分模板的原理最好能够理解,这样写的时候直接就能写出来了,也不会出错。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 typedef long long ll; 6 const int N = 100010; 7 int wood[N], n, k; 8 bool check(int h){ 9 int cnt = 0; 10 for(int i = 1; i <= n; i ++) 11 cnt += wood[i] / h; 12 if(cnt >= k) return true; 13 else return false; 14 } 15 int main(){ 16 ll sum = 0; 17 scanf("%d%d", &n, &k); 18 for(int i = 1; i <= n; i ++) scanf("%d", &wood[i]), sum += wood[i]; 19 if(sum < k){ //特判 20 cout << 0 << endl; 21 return 0; 22 } 23 sort(wood + 1, wood + 1 + n); 24 int l = 1, r = wood[n]; 25 while(l < r){ 26 int mid = l + r + 1 >> 1; 27 if(check(mid)) l = mid; 28 else r = mid - 1; 29 } 30 cout << l << endl; 31 return 0; 32 }