题目思路直接,用分桶法管理每一块的最大值和最小值就可以
#include<cstdio> #include<cmath> #include<iostream> #include<algorithm> #include<vector> #include<string> #include<map> #define DEBUG(x) cout << #x << " = " << x << endl using namespace std; const int N=50000+10; const int S=250; int a[N]; vector<int>vec[S]; int main() { ///freopen("in.txt","r",stdin); int n,q; scanf("%d%d",&n,&q); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); vec[i/(S+1)].push_back(a[i]); } for(int i=0;i<n/(S+1);i++){ sort(vec[i].begin(),vec[i].end()); } while(q--){ int L,R; scanf("%d%d",&L,&R); int Min=0x3f3f3f3f,Max=-1; int tl=L,tr=R; while(tl<=tr&&tl/(S+1)==L/(S+1)){ Min=min(a[tl],Min); Max=max(a[tl++],Max); } while(tl<=tr&&tr/(S+1)==R/(S+1)){ Min=min(a[tr],Min); Max=max(a[tr--],Max); } while(tl<=tr){ int bn=tl/(S+1); int s=0,e=vec[bn].size()-1; Min=min(vec[bn][s],Min); Max=max(vec[bn][e],Max); tl+=S; } printf("%d\n",Max-Min); } return 0; }