树状数组求区间最值不适合别人理解

#include 
using namespace std;
const int N = 1000005;
int tr[N], a[N];
int n, m;
int lowbit(int x) {
	return x & -x;
}
void add(int x, int c) {
	for (int i = x; i <= N; i+=lowbit(i)) {
		tr[i] = max(tr[i], c);
	}
}

int query(int l, int r) {
	if (l == r)return a[l];
	//判断区间我们维护的是r-lowbit(r) -r的区间最值 这里把区间分开 
	if (l < r - lowbit(r)) {
		return max(tr[r], query(l, r - lowbit(r)));
	} else return max(a[r], query(l, r - 1));

}
int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++)cin >> a[i], add(i, a[i]);
	while (m--) {
		int l, r;
		cin >> l >> r;
		cout << query(l, r) << endl;
	}
}

你可能感兴趣的:(c++,图论,算法)