编程知识 cdmana.com

【算法小结】ST算法求区间最值

pre文章:RMQ问题(ST算法)_hhhcbw的博客-CSDN博客_rmq

例题1:https://loj.ac/p/10119

代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
const int LogN = 20;
int f[maxn][LogN + 5], Log[maxn], a[maxn];
int main() {
	int n, m; cin >> n >> m;
	for (int i = 1; i <= n; i++) cin >> a[i];
	Log[0] = -1;
	for (int i = 1; i <= n; i++) Log[i] = Log[i >> 1] + 1;
	for (int i = 1; i <= n; i++) f[i][0] = a[i];
	for (int j = 1; j <= LogN; j++) {
		for (int i = 1; i + (1 << j) - 1 <= n; i++) {
			f[i][j] = max(f[i][j - 1], f[i + (1 << j - 1)][j - 1]);
		}
	}
	while (m--) {
		int x, y; cin >> x >> y;
		int z = Log[y - x + 1];
		cout << max(f[x][z], f[y - (1 << z) + 1][z]) << endl;
	}
	return 0;
}

版权声明
本文为[Ctrl AC]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_62434776/article/details/126128223

Scroll to Top