写一段C++语言的实现RMQ算法的代码
时间: 2023-03-24 17:00:50 浏览: 150
抱歉,我不确定您指的是哪种RMQ算法。一般来说,RMQ是“区间最小值查询”(Range Minimum Query)的缩写,其实现算法有多种。以下是两种常见的RMQ算法的实现代码,供参考:
1. 线段树RMQ算法
```python
class SegmentTree:
def __init__(self, arr):
self.tree = [0] * (4 * len(arr))
self.build(arr, 0, 0, len(arr) - 1)
def build(self, arr, index, left, right):
if left == right:
self.tree[index] = arr[left]
else:
mid = (left + right) // 2
self.build(arr, index * 2 + 1, left, mid)
self.build(arr, index * 2 + 2, mid + 1, right)
self.tree[index] = min(self.tree[index * 2 + 1], self.tree[index * 2 + 2])
def query(self, index, left, right, qleft, qright):
if left > qright or right < qleft:
return float('inf')
elif qleft <= left and qright >= right:
return self.tree[index]
else:
mid = (left + right) // 2
return min(self.query(index * 2 + 1, left, mid, qleft, qright),
self.query(index * 2 + 2, mid + 1, right, qleft, qright))
# 示例
arr = [1, 3, 2, 7, 9, 11]
tree = SegmentTree(arr)
print(tree.query(0, 0, len(arr) - 1, 1, 4)) # 输出2,即arr[2:5]的最小值
```
2. ST算法
```python
import math
class ST:
def __init__(self, arr):
n = len(arr)
k = int(math.log2(n))
self.table = [[0] * (k + 1) for _ in range(n)]
for i in range(n):
self.table[i][0] = arr[i]
for j in range(1, k + 1):
for i in range(n - 2 ** j + 1):
self.table[i][j] = min(self.table[i][j - 1], self.table[i + 2 ** (j - 1)][j - 1])
def query(self, left, right):
k = int(math.log2(right - left + 1))
return min(self.table[left][k], self.table[right - 2 ** k + 1][k])
# 示例
arr = [1, 3, 2, 7, 9, 11]
st = ST(arr)
print(st.query(1, 4)) # 输出2,即arr[2:5]的最小值
```
阅读全文