题目连接:http://poj.org/problem?id=3264
分块算法:将N个数 每sqrt(N)个数分成一个块,每一个块中加入一个value域保存这个块的最大值,查找的时候左右两个块在原序列上遍历查找最大值,中间的区间直接在预处理的块上查找最大值,
复杂度为:O(sqrt(N))
代码:
#include <cstdio>
#include <cmath>
#include <algorithm>
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 50000 + 5,INF = 2e9;
struct block{
int v;
}max_block[maxn],min_block[maxn];
int block_size,block_cnt;
int A[maxn],n,m;
void init_block(){
block_size = (int)sqrt((double)n);
block_cnt = (n + block_size - 1) / block_size;
for(int i = 0;i < block_cnt;++i){
int MIN = INF,MAX = -INF;
for(int j = i * block_size;j < (i + 1) * block_size && j < n;++j)
MIN = min(MIN,A[j]),MAX = max(MAX,A[j]);
max_block[i].v = MAX,min_block[i].v = MIN;
}
}
int Search(int l,int r){
int L = l / block_size + 1,R = r / block_size - 1;
int MIN = INF,MAX = -INF;
for(int i = L;i <= R;++i) MIN = min(MIN,min_block[i].v),MAX = max(MAX,max_block[i].v);
for(int i = l;i < L * block_size && i <= r;++i) MIN = min(MIN,A[i]),MAX = max(MAX,A[i]);
for(int i = r;i >= (R + 1) * block_size && i >= l;--i) MIN = min(MIN,A[i]),MAX = max(MAX,A[i]);
return MAX - MIN;
}
int main(){
while(~sf("%d %d",&n,&m)){
for(int i = 0;i < n;++i) sf("%d",&A[i]);
init_block();
while(m--){
int l,r;sf("%d %d",&l,&r);l--,r--;
pf("%d\n",Search(l,r));
}
}
}