使用稀疏表进行 C++ 范围求和查询
稀疏表是一种数据结构,用于提供范围查询的结果。它可以在 O(logN) 的复杂度内提供大多数范围查询的结果。对于最大范围查询,它也可以在 O(1) 内计算结果。
本教程将讨论使用稀疏表进行范围求和查询的问题,其中给定一个数组。我们需要找到例如范围 L 和 R 中所有元素的总和。
Input: arr[ ] = { 2, 4, 1, 5, 6, 3 }
query(1, 3),
query(0,2),
query(1, 5).
Output: 10
7
19
Input: arr[ ] = { 1, 2, 3, 4, 1, 4 }
query(0, 2),
query(2,4),
query(3, 5).
Output: 6
8
9查找解决方案的方法
首先,我们需要创建一个稀疏表来在其中搜索答案。在创建稀疏表时,我们使用一个二维数组来存储答案。在稀疏表中,我们将查询分解成 2 的幂。创建稀疏表后,我们在该表中搜索查询,并在满足 (Left_index + 2^n - 1 <= Right_index) 条件时将值持续添加到变量中,其中 n 是二维数组列的大小。
示例
以上方法的 C++ 代码
#include <bits/stdc++.h>
using namespace std;
// Maximum value of row of sparse table.
const int m = 1e5;
const int n = 16;
long long SPARSE[m][n + 1];
// query to be found with the help of a sparse table.
long long query(int l, int r){
long long sum = 0;
for (int i = n; i >= 0; i--) {
if (l + (1 << i) - 1 <= r) {
sum = sum + SPARSE[l][i];
l += 1 << i;
}
}
return sum;
}
int main(){
int arr[] = { 1, 2, 3, 4, 1, 4 };
int z = sizeof(arr) / sizeof(arr[0]);
// Building sparse table.
for (int i = 0; i < z; i++)
SPARSE[i][0] = arr[i];
for (int i = 1; i <= n; i++)
for (int j = 0; j <= z - (1 << j); j++)
SPARSE[j][i] = SPARSE[j][i - 1] + SPARSE[j + (1 << (i - 1))][i - 1];
cout <<"Sum: " << query(0, 2) << endl;
cout <<"Sum: " << query(2, 4) << endl;
cout <<"Sum: " << query(3, 5) << endl;
return 0;
}输出
Sum: 6 Sum: 8 Sum: 4
结论
在本教程中,我们讨论了创建稀疏表,这对范围查询非常有用。我们讨论了一种简单的解决此问题的方法,即通过创建稀疏表并从该表中获取查询结果。我们还讨论了此问题的 C++ 程序,我们也可以使用 C、Java、Python 等编程语言来实现。希望本教程对您有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP