题目链接:http://poj.org/problem?id=3264
——————————————————————————————————————————
题目简述:题意:给出一个长度为N<=10^6的数字串和M<=10^5个操作。操作有一种:求出[L, R]范围中,最大值与最小值的差值
——————————————————————————————————————————
题目关键字:线段树
——————————————————————————————————————————
题目思路:简单的线段树题目。其中find返回值是tree型(因为返回的是一个类型,无所谓局部变量的问题)
——————————————————————————————————————————
源代码:
#include<stdio.h>
struct tree
{
int max;
int min;
int left;
int right;
}tree[3000000];
int n = 0;
int cow[500010];
int mmax(int a,int b)
{
if(a>b) return a;
else return b;
}
int mmin(int a,int b)
{
if(a>b) return b;
else return a;
}
void init(int cur,int l,int r)
{
int m = (l+r)/2;
tree[cur].left = l;
tree[cur].right = r;
if(l == r)
{
tree[cur].max = cow[l];
tree[cur].min = cow[l];
}
else
{
init(cur*2,l,m);
init(cur*2+1,m+1,r);
tree[cur].max = mmax(tree[cur*2].max,tree[cur*2+1].max);
tree[cur].min = mmin(tree[cur*2].min,tree[cur*2+1].min);
}
}
struct tree find(int cur,int a,int b)
{
struct tree l,r,ans;
if(a == tree[cur].left && b == tree[cur].right)
return tree[cur];
else
{
int m = (tree[cur].left+tree[cur].right)/2;
if(a>m) return find(cur*2+1,a,b);
else if(b<=m) return find(cur*2,a,b);
else
{
l = find(cur*2,a,m);
r = find(cur*2+1,m+1,b);
ans.max = mmax(l.max,r.max);
ans.min = mmin(l.min,r.min);
return ans;
}
}
}
int main()
{
int i = 0,q = 0;
int a = 0,b = 0;
struct tree ans;
scanf("%d%d",&n,&q);
for(i = 1;i<=n;i++)
scanf("%d",&cow[i]);
init(1,1,n);
for(i = 0;i<q;i++)
{
scanf("%d%d",&a,&b);
ans = find(1,a,b);
printf("%d\n",ans.max-ans.min);
}
return 0;
}