/*
线段树
*/
#include<iostream>
using namespace std;
const int maxn = 1e8 + 10;
const int INF = 0x3f3f3f;
int n, tree[maxn];
void update(int k, int a) {
k += n - 1;
tree[k] = a;
while (k > 0) {
k = (k - 1) / 2;
tree[k] = min(tree[k * 2 + 1], tree[k * 2 + 2]);
}
}
int query(int a, int b, int l, int r, int k) {
if (a >= b)return INF; // 当 [a,b) 区间不合法时
if (a == l && b == r)return tree[k]; // 正好取到最小值的节点
if (b <= l && r <= a) { // 两个区间没有交集时
return INF;
}
int val1 = query(a, (l + r) / 2, l, (l + r) / 2, k * 2 + 1);
int val2 = query((l + r) / 2, b, (l + r) / 2, r, k * 2 + 2);
return min(val2, val1);
}
int main() {
cin >> n;
for (int i = 0;i < 2 * n - 1;i++) {
tree[i] = INF;
}
for (int i = 0;i < n;i++) {
int val;
cin >> val;
update(i, val);
}
for (int i = 0;i < 2 * n - 1;i++) {
cout << tree[i] << " ";
}
cout << "最小值 : " << endl;
cout << query(2, 4, 0, n, 0) << endl;
}
挑战程序设计-线段树
于 2022-03-31 15:01:00 首次发布