luogu 模板: https://www.luogu.com.cn/problem/P3865

静态区间最大值查询

#include <bits/stdc++.h>
using namespace std;
using LL = long long;
//mx[i][j] 表示从第 i 个位置开始 2^j 个数中的最大值
struct SparseTable{
	int n;
	vector<int> a;
	vector<vector<int>> mx;
	SparseTable(int n) : n(n), a(n + 1), mx(n + 1, vector<int>(log2(n) + 1)){}
	void init(){
		for (int i = 1; i <= n; i ++ ){
			mx[i][0] = a[i];
		}
		int k = log2(n);
		for (int j = 1; j <= k; j ++ ){
			for (int i = 1; i + (1 << j) - 1 <= n; i ++ ){
				mx[i][j] = max(mx[i][j - 1], mx[i + (1 << (j - 1))][j - 1]);
			}
		}
	}
	int queryMax(int L, int R){
		int k = log2(R - L + 1);
		return max(mx[L][k], mx[R - (1 << k) + 1][k]);
	}
};
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	int n, m;
	cin >> n >> m;
	SparseTable st(n);
	for (int i = 1; i <= n; i ++ ){
		cin >> st.a[i];
	}
	st.init();
	for (int i = 1; i <= m; i ++ ){
		int L, R;
		cin >> L >> R;
		cout << st.queryMax(L, R) << "\n";
	}
	return 0;
}
posted on 2022-04-24 11:24  Hamine  阅读(27)  评论(0编辑  收藏  举报