标签:span ref using tar map one color 查询 class
题意:
给定n个数,q次询问,查询当前区间最大值与最小值的差值
题解:
线段树模板题
区间查询最大值、最小值
代码:
#include<iostream> #include<stdio.h> #include<math.h> #include<algorithm> #include<vector> #include<map> using namespace std; typedef long long ll; const int maxn=1e5+5; struct node { int l,r; int minn,maxx; } tree[maxn<<2]; int n,a[maxn],q; void push_up(int x) { tree[x].maxx=max(tree[x<<1].maxx,tree[x<<1|1].maxx); tree[x].minn=min(tree[x<<1].minn,tree[x<<1|1].minn); } void build(int x,int l,int r) { tree[x].l=l,tree[x].r=r; if(l==r) { tree[x].maxx=tree[x].minn=a[l]; } else { int mid=(l+r)>>1; build(x<<1,l,mid); build(x<<1|1,mid+1,r); push_up(x); } } ll query(int x,int l,int r,int flag) { int L=tree[x].l,R=tree[x].r; if(l<=L && R<=r) { if(flag)return tree[x].maxx; else return tree[x].minn; } else { if(flag) { ll ans=0; int mid=(L+R)>>1; if(mid>=l)ans=max(ans,query(x<<1,l,r,flag)); if(mid<r)ans=max(ans,query(x<<1|1,l,r,flag)); push_up(x); return ans; } else { ll ans=0x3f3f3f3f; int mid=(L+R)>>1; if(mid>=l)ans=min(ans,query(x<<1,l,r,flag)); if(mid<r)ans=min(ans,query(x<<1|1,l,r,flag)); push_up(x); return ans; } } } int main() { scanf("%d%d",&n,&q); for(int i=1; i<=n; i++) scanf("%d",&a[i]); build(1,1,n); for(int i=1; i<=q; i++) { int l,r; scanf("%d%d",&l,&r); ll ans=query(1,l,r,1)-query(1,l,r,0); printf("%lld\n",ans); } return 0; }
标签:span ref using tar map one color 查询 class
原文地址:https://www.cnblogs.com/j666/p/11619801.html