Advertisement
aqibm

Untitled

Apr 6th, 2025
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. class BinaryArray {
  2. private:
  3. // Returns the smallest index id in [lo, hi] such that
  4. // query(lo, id) >= k, or returns -1 if no such index exists.
  5. int binsearch(int lo, int hi, int k) {
  6. int start = lo; // remember original start for the query
  7. while (lo < hi) {
  8. int mid = (lo + hi) / 2;
  9. int numOnes = query(start, mid); // number of 1's in subarray [start, mid]
  10. if (numOnes >= k) {
  11. hi = mid;
  12. } else {
  13. lo = mid + 1;
  14. }
  15. }
  16. // At this point lo == hi. Check if [start, lo] has at least k ones.
  17. if (query(start, lo) < k)
  18. return -1;
  19. return lo;
  20. }
  21.  
  22. public:
  23. // Returns a list of intervals (as pairs of indices) such that each interval contains exactly k ones.
  24. // It is assumed that the total number of 1's in the array is M (or at least M/k intervals exist).
  25. vector<pair<int, int>> getRanges(int M, int k) {
  26. vector<pair<int, int>> ans;
  27. int leftIndex = 1; // assuming 1-indexed positions
  28. while (leftIndex <= M) {
  29. int L = binsearch(leftIndex, M, k);
  30. if (L == -1)
  31. break;
  32. ans.push_back({leftIndex, L});
  33. leftIndex = L + 1;
  34. }
  35. return ans;
  36. }
  37.  
  38. // You must have an inbuilt query(L, R) function defined elsewhere.
  39. int query(int L, int R); // provided externally
  40. };
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement