水线段树,求给定区间最小值和最大值之差。
在写查询语句时少些了几个return,卡了下~o(╯□╰)o
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 50010
//#define max(a, b) (a>b?a:b)
//#define min(a, b) (a<b?a:b)
#define L(x) (x << 1)
#define R(x) (x << 1 | 1)
using namespace std;
int N, M;
typedef struct
{
int l, r;
int low, high;
}Node;
Node node[MAXN*4];
int height[MAXN];
void init()
{
memset(node, 0, sizeof(node));
}
void Build(int t, int l, int r)
{
node[t].l = l;
node[t].r = r;
if(node[t].r - node[t].l == 1)
{
node[t].low = node[t].high = height[node[t].l];
return;
}
int mid = (node[t].l + node[t].r) >> 1;
Build(L(t), l, mid);
Build(R(t), mid, r);
node[t].low = min(node[L(t)].low, node[R(t)].low);
node[t].high = max(node[L(t)].high, node[R(t)].high);
}
int QueryMin(int t, int l, int r)
{
if(node[t].l >= l && node[t].r <= r)
{
return node[t].low;
}
int mid = (node[t].l + node[t].r) >> 1;
if(l >= mid)
return QueryMin(R(t), l, r);
else if(r <= mid)
return QueryMin(L(t), l, r);
else
return min(QueryMin(L(t), l, mid), QueryMin(R(t), mid, r));
}
int QueryMax(int t, int l, int r)
{
if(node[t].l >= l && node[t].r <= r)
{
return node[t].high;
}
int mid = (node[t].l + node[t].r) >> 1;
if(l >= mid)
return QueryMax(R(t), l, r);
else if(r <= mid)
return QueryMax(L(t), l, r);
else
return max(QueryMax(L(t), l, mid), QueryMax(R(t), mid, r));
}
int main()
{
int i, a, b;
while(scanf("%d%d", &N, &M) != EOF)
{
for(i = 0; i < N; i++)
scanf("%d", &height[i]);
init();
Build(1, 0, N);
while(M--)
{
scanf("%d%d", &a, &b);
printf("%d\n", QueryMax(1, a-1, b) - QueryMin(1, a-1, b));
}
}
return 0;
}