NYOJ 119 士兵杀敌(三) RMQ ST
题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=119
思路:
ST在线 预处理O(nlogn) 查询O(1) 运行时间:828ms
可以用31-__builtin_clz(r-l+1)来代替k=(int)(log(r-l+1.0)/log(2.0)) 这样还能稍快20ms
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
const int maxn = 100005;
const int maxp = 17;
int maxnum[maxn][maxp],minnum[maxn][maxp];
inline void init(int n) {
for(int j=1; j<=17; ++j)
for(int i=1; i<=n; ++i)
if((i+(1<<j)-1)<=n) {
maxnum[i][j]=max(maxnum[i][j-1],maxnum[i+(1<<(j-1))][j-1]);
minnum[i][j]=min(minnum[i][j-1],minnum[i+(1<<(j-1))][j-1]);
}
}
int main() {
int n,m,l,r,k;
scanf("%d %d",&n,&m);
for(int i=1; i<=n; ++i) scanf("%d",&minnum[i][0]),maxnum[i][0]=minnum[i][0];
init(n);
for(int i=1; i<=m; ++i) {
scanf("%d %d",&l,&r);
k=(int)(log(r-l+1.0)/log(2.0));
printf("%d\n", max(maxnum[l][k],maxnum[r-(1<<k)+1][k]) - min(minnum[l][k],minnum[r-(1<<k)+1][k]));
}
return 0;
}