Mô tả bài toán
Cho mảng và X. Tìm chỉ số nhỏ nhất i sao cho prefixSum[i] ≥ X (prefixSum[i] = sum_{0..i} arr[j]).
Ví dụ
arr={5,2,9,4,1}, X=19 → prefixSum={5,7,16,20,21} → Output: 3 (prefixSum[3]=20 ≥19).
Giải thuật (Binary Lifting)
Xây dựng prefixSum. Khởi tạo pos=0. Duyệt bit từ log2(n) xuống 0: nếu pos+2^i < n và prefixSum[pos+2^i] < X thì pos += 2^i. Kết quả = pos+1.
Mã nguồn C++
#include <iostream>
#include <cmath>
using namespace std;
void genPrefix(int arr[], int pre[], int n) {
pre[0]=arr[0];
for (int i=1;i=0; i--) {
int next = pos + (1<
Đầu ra
The index of first elements of the array greater than the given number is 3