Cho mảng nums và ngưỡng k. Tìm ước số dương nhỏ nhất d sao cho tổng ceil(nums[i]/d) ≤ k.
Ví dụ: nums=[1,2,5,9], k=6 → d=5 (tổng = 1+1+1+2=5).
Thuật toán (Tìm kiếm nhị phân)
- Hàm
check(d): tính tổng ceiling chia chod, so vớik. - Binary search
dtrong [1, 1e7]. Nếucheck(mid)true →high=mid, elselow=mid+1.
Mã nguồn C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
bool ok(int x, vector& nums, int th) {
int sum=0;
for (int v : nums) sum += (v + x - 1) / x; // ceil
return sum <= th;
}
public:
int smallestDivisor(vector& nums, int th) {
int low=1, high=1e7;
while (low < high) {
int mid = low + (high-low)/2;
if (ok(mid, nums, th)) high = mid;
else low = mid+1;
}
return high;
}
};
int main() {
vector v = {1,2,5,9};
Solution ob;
cout << ob.smallestDivisor(v, 6); // 5
return 0;
}
Đầu vào / Đầu ra
Input: [1,2,5,9] 6
Output: 5