数列区间最大值

题目描述

思路

RMQ 问题 ST算法

代码

#include <cstdio>
#include <cstring>
#define max(a, b) ((a) > (b) ? (a) : (b))
int n, m;
int arr[100005];
int f[100005][21], log[100005];
inline int read() {
	int s = 0;
	char ch = getchar();
	while (ch < '0' || ch > '9') ch = getchar();
	while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s;
}
int main() {
	n = read(), m = read(); 
	log[0] = -1;
	for (int i = 1; i <= n; ++i) {
		arr[i] = read();
		log[i] = log[i >> 1] + 1;
		f[i][0] = arr[i];
	}
	for (int i = 1; i <= 20; ++i) {
		for (int j = 1; j + (1 << i) - 1 <= n; ++j) {
			f[j][i] = max(f[j][i - 1], f[j + (1 << (i - 1))][i - 1]);
		} 
	}
	for (int i = 1, a, b, c; i <= m; ++i) {
		a = read(), b = read();
		c = log[b - a + 1];
		printf("%d\n", max(f[a][c], f[b - (1 << c) + 1][c]));
	}
	return 0;
}
posted @ 2019-09-09 11:29  cabbage-leaf  阅读(266)  评论(0编辑  收藏  举报