1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| #include<iostream> #include<algorithm> #include<vector> using namespace std; template<typename T>inline void read(T &x){ x=0;T f=1;char ch=getchar(); while(ch<48||ch>57){if(ch=='-'){f=-1;}ch=getchar();} while(ch>=48&&ch<=57){x=x*10+ch-48;ch=getchar();} x*=f; } template<typename T>inline void write(T x){ if(x<0) putchar('-'),x=-x; if(x>9) write(x/10); putchar(x%10+48); } const int N=1e5+8; const int M=3E5+8; #define lowbit(x) (x)&(-x) int t[N],a[N]; int ans[M]; int n,m; vector<pair<int,int> > Q[N]; void update(int pos,int val){ for(int i=pos;i;i-=lowbit(i)){ t[i]=min(t[i],val); } } int ask(int pos){ int res=1e9; for(int i=pos;i<=n;i+=lowbit(i)){ res=min(res,t[i]); } return res; } int ls[N*20],rs[N*20],mx[N*20],cnt,rt; void modify(int &u,int l,int r,int pos,int v){ if(!u) u=++cnt; mx[u]=max(mx[u],v); if(l==r) return ; int mid=l+r>>1; if(pos<=mid) modify(ls[u],l,mid,pos,v); else modify(rs[u],mid+1,r,pos,v); } int query(int u,int l,int r,int ql,int qr){ if(!u) return 0; if(ql<=l&&r<=qr) return mx[u]; int v=0; int mid=l+r>>1; if(ql<=mid) v=max(v,query(ls[u],l,mid,ql,qr)); if(qr>mid) v=max(v,query(rs[u],mid+1,r,ql,qr)); return v; } void solve(){ for(int i=1;i<=n;i++){ t[i]=1e9; } for(int i=1;i<=cnt;i++){ ls[i]=rs[i]=mx[i]=0; } cnt=rt=0; for(int i=1;i<=n;i++){ int pos=query(rt,0,1e9,a[i],1e9); while(pos){ update(pos,a[pos]-a[i]); pos=query(rt,0,1e9,a[i],(a[i]+a[pos])/2-(((a[i]+a[pos])%2==0)?1:0)); } modify(rt,0,1e9,a[i],i); for(int j=0;j<Q[i].size();j++){ ans[Q[i][j].second]=min(ans[Q[i][j].second],ask(Q[i][j].first)); } } } int main(){ read(n); for(int i=1;i<=n;i++) read(a[i]); read(m); for(int i=1;i<=m;i++){ int l,r; read(l),read(r); ans[i]=1e9; Q[r].push_back({l,i}); } solve(); for(int i=1;i<=n;i++){ a[i]=1e9-a[i]; } solve(); for(int i=1;i<=m;i++){ write(ans[i]),putchar('\n'); } return 0; }
|