稀疏矩阵 实现O(nlogn)预处理 O(1)查询 (ST_RMQ模板)

Code:

#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>

using namespace std;

const int maxn = 100007;
int dp_max[maxn][25];//dp_max[i][j]表示arr[i], arr[i+1], ..., arr[i+2^j-1]中的最大值
int arr[maxn];
int n, m;
void init() {
	for (int i=1;i<=n;i++) {
		dp_max[i][0] = arr[i];
	}
	for (int j=1;j<=20;j++) {//2^20 大于maxn就行了
		for (int i=1;i + (1 << j) - 1 <=n;i++) {
			dp_max[i][j] = max(dp_max[i][j-1], dp_max[i + (1 << (j - 1))][j-1]);
		}
	}
}
void query(int from, int to) {
	int s;
	while ((1 << (s + 1) ) <= (to - from + 1))//或者直接s = log2(to - from + 1);
		s++;
	cout<<"max=";
	cout<<max(dp_max[from][s], dp_max[to - (1 << s) + 1][s])<<endl;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin>>n>>m;
	for (int i=1;i<=n;i++) {
		cin>>arr[i];
	}
	init();
	int from, to;
	while (m--) {
		cin>>from>>to;
		query(from, to);
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值