好吧!
对于初学线段树的我来说:线段树真心不容易!
这道题搞了好久!还是一个蠢方法!不过至少AC了!呵呵!很开心!或许这就是ACM的魅力所在之处吧!
当你认为你搞出一道很得意的题目时,那种内心的激动是别人无法理解的!
嘿嘿····!
加油哦!
#include<stdio.h>
#define N 50010
#define max(a,b) a>b?a:b
#define min(a,b) a<b?a:b
struct node
{
int x,y;
int max;
int min;
}aaa[N*3],aa[N*3];
int num[N];
int CreatTreemax(int t,int x,int y)
{
aaa[t].x=x;
aaa[t].y=y;
if(x==y)
{
return aaa[t].max=num[x];;
}
int temp=2*t;
int mid=(x+y)/2;
int a,b;
a=CreatTreemax(temp,x,mid);
b=CreatTreemax(temp+1,mid+1,y);
return aaa[t].max=max(a,b);
}
int CreatTreemin(int t,int x,int y)
{
aa[t].x=x;
aa[t].y=y;
if(x==y)
{
return aa[t].min=num[x];;
}
int temp=2*t;
int mid=(x+y)/2;
int a,b;
a=CreatTreemin(temp,x,mid);
b=CreatTreemin(temp+1,mid+1,y);
return aa[t].min=min(a,b);
}
int FindTreemax(int t,int x,int y)
{
if(aaa[t].x>y||aaa[t].y<x)
return 0;
if(x<=aaa[t].x&&y>=aaa[t].y)
return aaa[t].max;
int a,b;
int temp=2*t;
a=FindTreemax(temp,x,y);
b=FindTreemax(temp+1,x,y);
return max(a,b);
}
int FindTreemin(int t,int x,int y)
{
if(aa[t].x>y||aa[t].y<x)
return 10000000;
if(aa[t].x>=x&&aa[t].y<=y)
return aa[t].min;
int a,b;
int temp=2*t;
a=FindTreemin(temp,x,y);
b=FindTreemin(temp+1,x,y);
return min(a,b);
}
int main()
{
int x,y,i;
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%d",&num[i]);
CreatTreemax(1,1,n);
CreatTreemin(1,1,n);
while(m--)
{
scanf("%d%d",&x,&y);
printf("%d\n",FindTreemax(1,x,y)-FindTreemin(1,x,y));
}
}
return 0;
}
题目链接:http://poj.org/problem?id=3264