标签:
题意:求 一段 区间 的 最大值和最小值 的差值
题解:线段树
碎碎念:某种意义上说,第一道自己手写的线段树,总之蛮好~
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> using namespace std; const int MAXN = 50000+10; const int INF = 1000000; int arr[MAXN]; int segx[MAXN<<2]; int segi[MAXN<<2]; void build(int l,int r,int x){ if(l==r){ segx[x] = arr[l]; segi[x] = arr[l]; return; } int mid = (l+r)>>1; build(l,mid,x<<1); build(mid+1,r,x<<1|1); segx[x]= max(segx[x<<1],segx[x<<1|1]); segi[x]= min(segi[x<<1],segi[x<<1|1]); return; } int mi,mx; void quercy(int l,int r,int x,int L,int R){ if(l>=L && r<=R){ mi = min(mi,segi[x]); mx = max(mx,segx[x]); return; } int mid = (l+r)>>1; if(mid>=L){ quercy(l,mid,x<<1,L,R); } if(mid<R){ quercy(mid+1,r,x<<1|1,L,R); } } int main(){ // freopen("input.txt","r",stdin); int n,q; while(~scanf("%d%d",&n,&q)){ for(int i = 1;i<=n;i++){ scanf("%d",&arr[i]); } build(1,n,1); while(q--){ int l,r; scanf("%d%d",&l,&r); mi = INF; mx = 1; quercy(1,n,1,l,r); printf("%d\n",mx-mi); } } return 0; }
题解2:平方分割
分桶法:把一排物品或平面分成桶,每个桶维护自己的信息
把一段区间 维护成 一个桶,然后求其最值
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> using namespace std; const int MAXN = 50000+10; const int INF = 1000000; int arr[MAXN]; const int sz = 200; int bucket[260][sz]; int MX[260]; int MI[260]; int main(){ // freopen("input.txt","r",stdin); int n,q; while(~scanf("%d%d",&n,&q)){ fill(MI,MI+260,INF); fill(MX,MX+260,1); for(int i = 1;i<=n;i++){ int x = i/sz; int y = i%sz; scanf("%d",&bucket[x][y]); MI[x] = min(MI[x],bucket[x][y]); MX[x] = max(MX[x],bucket[x][y]); } bucket[0][0] = bucket[0][1]; while(q--){ int l,r; scanf("%d%d",&l,&r); int mi = INF; int mx = 1; int x1 = l/sz; int y1= l%sz; int x2 = r/sz; int y2 = r%sz; if(x1==x2){ for(int i = y1;i<=y2;i++){ mi = min(bucket[x1][i],mi); mx = max(bucket[x1][i],mx); } printf("%d\n",mx-mi); continue; } for(int i = y1;i < sz;i++){ mi = min(bucket[x1][i],mi); mx = max(bucket[x1][i],mx); } for(int i = 0;i<=y2;i++){ mi = min(bucket[x2][i],mi); mx = max(bucket[x2][i],mx); } for(int i=x1+1;i<x2;i++){ mi = min(MI[i],mi); mx = max(MX[i],mx); } printf("%d\n",mx-mi); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/hanbinggan/p/4719445.html