Table of Contents
grammar
algorithm
method 1
Example
Output
Method 2
in conclusion
Home Backend Development C++ Query the lower bound of K using the prefix and array update of the tree array

Query the lower bound of K using the prefix and array update of the tree array

Sep 04, 2023 pm 05:33 PM
tree array Prefixes and arrays Query lower bound

Query the lower bound of K using the prefix and array update of the tree array

A primary sequence sum array is a collection that accumulates the sum of interleaved elements until a specific index is reached. This is a strategy widely used in combinatorial refactoring to optimize time complexity. Tree arrays, also known as Binary Index Trees (BITs), are a database form that efficiently updates elements and computes the sum of previous sequences in logarithmic time complexity.

In this article, we will discuss how to use a modern improvement of Fenwick Tree in C to reveal the smaller limit bound of a given value, called K, from a series summed array.

grammar

The syntax defines two functions, update and query, and a main function for the Fenwick tree, a data structure used for efficient range query and update operations. The update function accepts an index idx, a value val, the size of the array n, and the Fenwick tree array BIT. It updates the Fenwick tree by adding val to the node at index idx and all its ancestors. The query function accepts an index idx and Fenwick tree array BIT. It returns the cumulative sum from the root node to the node with index idx. The main function declares the size n of the array, the prefix and array arr, and the Fenwick tree array BIT initialized to 0.

void update(int idx, int val, int n, int BIT[]) {
   while (idx <= n) {
      BIT[idx] += val;
      idx += (idx & -idx);
   }
}
int query(int idx, int BIT[]) {
   int sum = 0;
   while (idx > 0) {
      sum += BIT[idx];
      idx -= (idx & -idx);
   }
   return sum;
}
// Driver code
int main() {
   int n; 
   int arr[n+1];
   int BIT[n+1] = {0}; 
   return 0;
}
Copy after login

algorithm

To determine the minimum value of K in the prefix and array with Fenwick tree update, follow the following complex steps -

  • Instantiate a Fenwick tree (BIT) of size n 1, initializing all elements to 0.

  • Use the update() function to modify the Fenwick Tree with the given prefix and array.

  • Perform a query on the Fenwick tree to determine the lower bound of K. Iterate starting from the most significant bit in the binary representation of n to the least significant bit. Use the query() function to verify whether the current prefix sum is less than or equal to K. If this condition is met, the current prefix sum is subtracted from K and the index is updated to move to the next bit. If the condition is not met, move to the next bit without updating the index.

  • After all bits have been traversed, the index will represent the prefix and the lower bound of K in the array.

  • Output the obtained index as the lower bound of K.

method

  • Method 1 − Perform binary search on Fenwick tree. In this method, we perform a binary search on the Fenwick tree to find the lower bound of K.

  • Method 2 - Binary search with delayed propagation on Fenwick tree.

method 1

To solve this problem, we first set the left and right pointers to 1 and n respectively (indicating the size of the prefix and array), and then use a binary search strategy to determine the index corresponding to the largest prefix sum less than or equal to K i. Then, depending on whether the value of prefix sum [i] is less than or equal to K, the position of the left pointer or the right pointer is updated.

Example

The basic mechanism of this code is to utilize a data structure called Fenwick Tree (also known as Binary Indexed Tree). Its purpose is to determine the lower bound of the specified value 'k' in the prefix sum array. This is accomplished by constructing a Fenwick Tree using an update function that merges the prefix and value of each element in the array into the corresponding position in the Fenwick Tree.

The findLowerBound function then uses a binary search algorithm to find the lower bound of "k" in the prefix and array by querying the function. This function calculates the cumulative sum of values ​​up to the current index in the Fenwick tree. Eventually, the code ends up identifying the prefix and the index of the lower bound of "k" in the array, and displays the result to the console.

#include <iostream>
using namespace std;
void update(int i, int v, int n, int b[]) {
    while (i <= n) {
        b[i] += v;
        i += (i & -i);
    }
}
int query(int i, int b[]) {
    int s = 0;
    while (i > 0) {
        s += b[i];
        i -= (i & -i);
    }
    return s;
}
int findLowerBound(int k, int n, int p[], int b[]) {
    int l = 1, r = n, idx = 0;
    while (l <= r) {
        int m = (l + r) / 2;
        int msum = query(m, b);
        if (msum <= k) {
            idx = m;
            l = m + 1;
        } else {
            r = m - 1;
        }
    }
    return idx;
}
int main() {
    int n = 5;
    int p[] = {0, 1, 3, 6, 10, 15};
    int b[n + 1] = {0};
    for (int i = 1; i <= n; i++) {
        update(i, p[i], n, b);
    }
    int k = 10, idx;
    idx = findLowerBound(k, n, p, b);
    cout << "The lower bound of " << k << " is at index " << idx << " in the prefix sum array." << endl;
    return 0;
}
Copy after login

Output

The lower bound of 10 is at index 3 in the prefix sum array.
Copy after login

Method 2

To further optimize Fenwick trees, a technique called lazy propagation can be used. This approach entails deferring updates to the Fenwick Tree until they are actually needed, thereby reducing the number of updates and making the query process more efficient.

Example

The code provides a solution for locating the lower bound of a given value K in a prefix sum array. A prefix sum array is an array where each element is the sum of the elements from index 0 to that index in the original array. The lower bound is the first index in the prefix sum array such that the sum of the elements up to that index equals or exceeds K. The solution uses Fenwick tree data structure and delay propagation technique to enhance the efficiency of the solution. The code includes functions for modifying Fenwick trees, calculating prefix sums, and finding lower bounds. The code also initializes prefix sum arrays, Fenwick trees, and delayed propagation arrays. Finally, it outputs the prefix and the lower bound of K in the array.

#include  <iostream>
#include  <cstring>
using namespace std;

void update(int idx, int val, int n, int ft[], int lz[]) {
   while (idx  <= n) ft[idx] += val, idx += (idx & -idx);
}

int getPrefixSum(int idx, int ft[]) {
   int sum = 0;
   while (idx > 0) sum += ft[idx], idx -= (idx & -idx);
   return sum;
}

int findLowerBound(int K, int n, int ps[], int ft[], int lz[]) {
   int l = 1, r = n, lb = 0;
   while (l  <= r) {
      int m = (l + r) / 2, s = getPrefixSum(m, ft) + lz[m];
      if (s  <= K) lb = m, l = m + 1;
      else r = m - 1;
   }
   return lb;
}

int main() {
   int n = 5;
   int ps[] = {0, 1, 3, 6, 10, 15};
   int ft[n + 1], lz[n + 1]; memset(ft, 0, sizeof(ft)); memset(lz, 0, sizeof(lz));
   for (int i = 1; i  <= n; i++) update(i, ps[i] - ps[i - 1], n, ft, lz);
   int K = 10;
   int lb = findLowerBound(K, n, ps, ft, lz);
   cout << "For the given array with size " << n << " and prefix sum array [";
   for (int i = 1; i <= n; i++) {
      cout << ps[i];
      if (i < n) cout << ", ";
   }
   cout << "], the lower bound of " << K << " is at index " << lb << " in the prefix sum array." << endl;
   return 0;
}
Copy after login

Output

For the given array with size 5 and prefix sum array [1, 3, 6, 10, 15], the lower bound of 10 is at index 4 in the prefix sum array.
Copy after login

in conclusion

A discussion on mining elusive K-value thresholds from carefully designed prefixes and arrays, enhanced by an update that takes advantage of the clever Fenwick tree algorithm from the world of C programming. Dive into the complexities of two efficient methods: binary search on Fenwick trees and binary search on Fenwick trees with lazy propagation. Carefully choose the most appropriate method based on the specific requirements and constraints of your particular problem. Hopefully this sheds light on the conceptualization and implementation of the elusive task of finding a lower bound on K from an array of prefix sums with updates, leveraging the unparalleled power of Fenwick trees in the C domain.

The above is the detailed content of Query the lower bound of K using the prefix and array update of the tree array. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C language data structure: data representation and operation of trees and graphs C language data structure: data representation and operation of trees and graphs Apr 04, 2025 am 11:18 AM

C language data structure: The data representation of the tree and graph is a hierarchical data structure consisting of nodes. Each node contains a data element and a pointer to its child nodes. The binary tree is a special type of tree. Each node has at most two child nodes. The data represents structTreeNode{intdata;structTreeNode*left;structTreeNode*right;}; Operation creates a tree traversal tree (predecision, in-order, and later order) search tree insertion node deletes node graph is a collection of data structures, where elements are vertices, and they can be connected together through edges with right or unrighted data representing neighbors.

The truth behind the C language file operation problem The truth behind the C language file operation problem Apr 04, 2025 am 11:24 AM

The truth about file operation problems: file opening failed: insufficient permissions, wrong paths, and file occupied. Data writing failed: the buffer is full, the file is not writable, and the disk space is insufficient. Other FAQs: slow file traversal, incorrect text file encoding, and binary file reading errors.

What are the basic requirements for c language functions What are the basic requirements for c language functions Apr 03, 2025 pm 10:06 PM

C language functions are the basis for code modularization and program building. They consist of declarations (function headers) and definitions (function bodies). C language uses values ​​to pass parameters by default, but external variables can also be modified using address pass. Functions can have or have no return value, and the return value type must be consistent with the declaration. Function naming should be clear and easy to understand, using camel or underscore nomenclature. Follow the single responsibility principle and keep the function simplicity to improve maintainability and readability.

How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial How to calculate c-subscript 3 subscript 5 c-subscript 3 subscript 5 algorithm tutorial Apr 03, 2025 pm 10:33 PM

The calculation of C35 is essentially combinatorial mathematics, representing the number of combinations selected from 3 of 5 elements. The calculation formula is C53 = 5! / (3! * 2!), which can be directly calculated by loops to improve efficiency and avoid overflow. In addition, understanding the nature of combinations and mastering efficient calculation methods is crucial to solving many problems in the fields of probability statistics, cryptography, algorithm design, etc.

Function name definition in c language Function name definition in c language Apr 03, 2025 pm 10:03 PM

The C language function name definition includes: return value type, function name, parameter list and function body. Function names should be clear, concise and unified in style to avoid conflicts with keywords. Function names have scopes and can be used after declaration. Function pointers allow functions to be passed or assigned as arguments. Common errors include naming conflicts, mismatch of parameter types, and undeclared functions. Performance optimization focuses on function design and implementation, while clear and easy-to-read code is crucial.

Concept of c language function Concept of c language function Apr 03, 2025 pm 10:09 PM

C language functions are reusable code blocks. They receive input, perform operations, and return results, which modularly improves reusability and reduces complexity. The internal mechanism of the function includes parameter passing, function execution, and return values. The entire process involves optimization such as function inline. A good function is written following the principle of single responsibility, small number of parameters, naming specifications, and error handling. Pointers combined with functions can achieve more powerful functions, such as modifying external variable values. Function pointers pass functions as parameters or store addresses, and are used to implement dynamic calls to functions. Understanding function features and techniques is the key to writing efficient, maintainable, and easy to understand C programs.

C language multithreaded programming: a beginner's guide and troubleshooting C language multithreaded programming: a beginner's guide and troubleshooting Apr 04, 2025 am 10:15 AM

C language multithreading programming guide: Creating threads: Use the pthread_create() function to specify thread ID, properties, and thread functions. Thread synchronization: Prevent data competition through mutexes, semaphores, and conditional variables. Practical case: Use multi-threading to calculate the Fibonacci number, assign tasks to multiple threads and synchronize the results. Troubleshooting: Solve problems such as program crashes, thread stop responses, and performance bottlenecks.

How to output a countdown in C language How to output a countdown in C language Apr 04, 2025 am 08:54 AM

How to output a countdown in C? Answer: Use loop statements. Steps: 1. Define the variable n and store the countdown number to output; 2. Use the while loop to continuously print n until n is less than 1; 3. In the loop body, print out the value of n; 4. At the end of the loop, subtract n by 1 to output the next smaller reciprocal.

See all articles