


Using a tree array (offline query), calculate the number of elements greater than K in the range L to R
In the field of computer science, we have to deal with large data sets, which include query select and update operations. Performing these operations in real-time with low time complexity is a challenging task for developers.
Using Fenwick trees is an effective way to solve these range-based query problems.
Fenwick Tree is a data structure that can efficiently update elements and calculate the prefix sum of numbers in a table. It is also called a binary index tree.
In this article, we will discuss how to use Fenwick tree to find the number of elements greater than K in the range L to R.
Input and output scenarios
Suppose you have an array with N elements, and you want to find the number of elements in the array that are greater than K in the range L to R.
Input: arr = {1, 15, 12, 13, 6, 18, 14, 10, 23, 41, 16, 9} N = 11, K = 17, L = 1, R = 8 Output: 2
What is offline query?
Offline query is a query operation performed on a predetermined data set. In other words, these operations are performed only on those datasets that are not further modified while processing the query.
Use Fenwick Tree
Here we will use a Fenwick tree, which has vectors at each node containing all the elements of the array in order. We then use binary search to answer each query and count the number of elements.
Create two functions, updateTree() and total(), for updating and retrieving the prefix sum in BIT respectively.
Next, create another function that will count elements in the range L to R that are greater than "K". This function accepts the input values "arr", "N", "L", "R" and "K" ".
The count is calculated by subtracting the cumulative sum of K from the cumulative sum of the maximum range N.
To exclude out-of-range elements, subtract the cumulative sum of L-1 (if L is greater than 1).
Example
#include <iostream> #include <vector> using namespace std; // Updating the Fenwick Tree void updateTree(vector<int>& BIT, int index, int value) { while (index < BIT.size()) { BIT[index] += value; index += index & -index; } } int total(vector<int>& BIT, int index) { int result = 0; while (index > 0) { result += BIT[index]; index -= index & -index; } return result; } // Counting the number of elements int elementsGreaterThanK(vector<int>& arr, int N, int K, int L, int R) { vector<int> BIT(N+1, 0); for (int i = L; i <= R; i++) { updateTree(BIT, arr[i], 1); } int count = total(BIT, N) - total(BIT, K); if (L > 1) { count -= total(BIT, L-1); } return count; } int main() { vector<int> arr = {0, 5, 2, 3, 6, 8, 7, 1, 8, 4, 6, 9}; int N = 11; // Total range of values int K = 4; // Highest value int L = 1; // Start index of the range int R = 8; // End index of the range int count = elementsGreaterThanK(arr, N, K, L, R); cout << "Number of elements greater than " << K << " in the range [" << L << ", " << R << "]: " << count << endl; return 0; }
Output
Number of elements greater than 4 in the range [1, 8]: 5
alternative method
Here we will create a separate vector to store the query. Each query consists of two variables, index and val. index is used to store the position in the array, and val is used to store the value of the element at that index. This approach enables developers to perform a variety of query operations. Additionally, we use BIT to count the number of elements greater than K for each query.
Example
#include <iostream> #include <vector> using namespace std; struct Query { int index; int val; }; void updateTree(vector<int>& BIT, int index, int value) { while (index < BIT.size()) { BIT[index] += value; index += index & -index; } } int total(vector<int>& BIT, int index) { int result = 0; while (index > 0) { result += BIT[index]; index -= index & -index; } return result; } vector<int> elementsGreaterThanK(vector<int>& arr, vector<Query>& queries, int K) { int N = arr.size(); vector<int> BIT(N+1, 0); vector<int> result; for (int i = 0; i < N; i++) { updateTree(BIT, i+1, (arr[i] > K) ? 1 : 0); } for (auto query : queries) { if (query.val > K) { result.push_back(total(BIT, query.index)); } else { result.push_back(0); } } return result; } int main() { vector<int> arr = {3, 14, 32, 7, 11, 5, 8, 6, 16, 2, 15}; vector<Query> queries = {{2, 4}, {5, 3}, {3, 6}, {0, 3}}; int K = 2; vector<int> counts = elementsGreaterThanK(arr, queries, K); for (int count : counts) { cout << "Number of elements greater than " << K << ": " << count << endl; } return 0; }
Output
Number of elements greater than 2: 2 Number of elements greater than 2: 5 Number of elements greater than 2: 3 Number of elements greater than 2: 0
in conclusion
We can simply iterate the array from index L to R and increment by 1 every time the array element is greater than K in order to find the answer to each query. However, in order to reduce the time complexity, we use Fenwick tree to perform such query operations. We can also use Line Segment Tree and Sparse Table instead of Fenwick tree to perform such query operations.
The above is the detailed content of Using a tree array (offline query), calculate the number of elements greater than K in the range L to R. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 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.

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.

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.

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.

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.

Although C and C# have similarities, they are completely different: C is a process-oriented, manual memory management, and platform-dependent language used for system programming; C# is an object-oriented, garbage collection, and platform-independent language used for desktop, web application and game development.

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.
