给你一个长度为n的序列a[N] (1 ≤ N ≤ 50000),询问Q(1 ≤ Q ≤ 200000) 次,每次输出【L, R】区间最大值与最小值的差是多少。
so easy~
so easy~
so easy~
多组用例
第一行是两个整数 N,Q
然后是N个数a[i] 保证a[i] 都小于1e9
然后是Q个询问 每次给你L,R 保证(1<=L<=R<= N)
6 3 1 7 3 4 2 5 1 5 4 6 2 2
6 3 0
好吧,都说了,so easy。
对于极值问题,如果不是动态的(没有后续更新),最好用RMQ。写线段树还是有点繁琐的,因为对于极值问题,RMQ和线段树的复杂度都差不多。当然专攻线段树也行,接下来用两种写法来完成,区间极值的操作。
//RMQ 3500ms
#include <math.h>
#include <stdio.h>
#define Max(x,y) ((x)>(y)?(x):(y))
#define Min(x,y) ((x)<(y)?(x):(y))
using namespace std;
const int maxn = 5*1e4+5;
int maxnum[maxn][22];
int minnum[maxn][22];
void RMQ(int n) {
for(int j = 1; j < 21; 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, Q;
int l, r;
scanf("%d %d", &N, &Q);
for(int i = 1; i <= N; i++) {
scanf("%d", &maxnum[i][0]);
minnum[i][0] = maxnum[i][0];
}
RMQ(N);
while(Q--) {
scanf("%d %d", &l, &r);
int k = (int)(log(r-l+1.0)/log(2.0));
int mx = Max(maxnum[l][k], maxnum[r-(1<<k)+1][k]);
int mn = Min(minnum[l][k], minnum[r-(1<<k)+1][k]);
printf("%d\n", mx-mn);
}
return 0;
}
//线段树 3485ms
#include <stdio.h>
#define Max(x, y) ((x)>(y)?(x):(y))
#define Min(x, y) ((x)<(y)?(x):(y))
#define inf 0x3f3f3f3f
const int maxn = 5*1e5+5;
struct Node {
int l, r;
int mx, mn;
}node[maxn<<2];
void Build(int i, int l, int r) {
node[i].l = l;
node[i].r = r;
if(l == r) {
scanf("%d", &node[i].mx);
node[i].mn = node[i].mx;
return ;
}
int m = (l+r)/2;
Build(i<<1, l, m);
Build(i<<1|1, m+1, r);
node[i].mn = Min(node[i<<1].mn, node[i<<1|1].mn);
node[i].mx = Max(node[i<<1].mx, node[i<<1|1].mx);
return ;
}
int mn = inf, mx = -inf;
void Query(int i, int l, int r) {
if(node[i].l == l && node[i].r == r) {
mn = Min(mn, node[i].mn);
mx = Max(mx, node[i].mx);
return ;
}
i = i<<1;
if(l <= node[i].r) {
if(r <= node[i].r)
Query(i, l, r);
else
Query(i, l, node[i].r);
}
i++;
if(r >= node[i].l) {
if(l >= node[i].l)
Query(i, l, r);
else
Query(i, node[i].l, r);
}
}
int main() {
int N, M;
int l, r;
scanf("%d %d", &N, &M);
Build(1, 1, N);
while(M--) {
scanf("%d %d", &l, &r);
mn = inf;
mx = -inf;
Query(1, l, r);
printf("%d\n", mx-mn);
}
return 0;
}