POJ-3264-Balanced Lineup
http://poj.org/problem?id=3264
线段树,求区间的最大值与最小值之差
#include<stdio.h> #include<string.h> #include<stdlib.h> #define N 50005 #define INF 0x7ffffff int num[N]; struct cam { int x; //起点 int y; //终点 int min; //最小值 int max; //最大值 }list[N*4]; int Min(int x,int y) { return x<y?x:y; } int Max(int x,int y) { return x>y?x:y; } void build(int k,int x,int y) { int mid; list[k].x=x; list[k].y=y; if(list[k].x==list[k].y) { list[k].min=num[x]; list[k].max=num[x]; return; } mid=(x+y)/2; build(k<<1,x,mid); build(k<<1|1,mid+1,y); list[k].min=Min(list[k<<1].min,list[k<<1|1].min); list[k].max=Max(list[k<<1].max,list[k<<1|1].max); return; } int findmin(int k,int x,int y) { int mid; if(list[k].x==x&&list[k].y==y) return list[k].min; mid=(list[k].x+list[k].y)/2; if(x>mid) return findmin(k<<1|1,x,y); else if(y<=mid) return findmin(k<<1,x,y); return Min(findmin(k<<1,x,mid),findmin(k<<1|1,mid+1,y)); } int findmax(int k,int x,int y) { int mid; if(list[k].x==x&&list[k].y==y) return list[k].max; mid=(list[k].x+list[k].y)/2; if(x>mid) return findmax(k<<1|1,x,y); else if(y<=mid) return findmax(k<<1,x,y); return Max(findmax(k<<1,x,mid),findmax(k<<1|1,mid+1,y)); } int main() { int i,n,m; int x,y; scanf("%d%d",&n,&m); for(i=1;i<=n;i++) scanf("%d",&num[i]); build(1,1,n); while(m--) { scanf("%d%d",&x,&y); printf("%d\n",findmax(1,x,y)-findmin(1,x,y)); } return 0; }