Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 297 Accepted Submission(s): 152
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 const int maxn = 100010; 5 struct node { 6 int lt,rt,minv,maxv; 7 } tree[maxn<<2]; 8 int d[maxn]; 9 inline void pushup(int v) { 10 tree[v].minv = min(tree[v<<1].minv,tree[v<<1|1].minv); 11 tree[v].maxv = max(tree[v<<1].maxv,tree[v<<1|1].maxv); 12 } 13 void build(int lt,int rt,int v) { 14 tree[v].lt = lt; 15 tree[v].rt = rt; 16 if(lt == rt) { 17 tree[v].minv = tree[v].maxv = d[lt]; 18 return; 19 } 20 int mid = (lt + rt)>>1; 21 build(lt,mid,v<<1); 22 build(mid+1,rt,v<<1|1); 23 pushup(v); 24 } 25 int query(int lt,int rt,int v,bool qmax) { 26 if(lt <= tree[v].lt && rt >= tree[v].rt) 27 return qmax?tree[v].maxv:tree[v].minv; 28 int ret = qmax?INT_MIN:INT_MAX; 29 if(lt <= tree[v<<1].rt) 30 ret = qmax?max(ret,query(lt,rt,v<<1,qmax)):min(ret,query(lt,rt,v<<1,qmax)); 31 if(rt >= tree[v<<1|1].lt) 32 ret = qmax? max(ret,query(lt,rt,v<<1|1,qmax)):min(ret,query(lt,rt,v<<1|1,qmax)); 33 return ret; 34 } 35 int main() { 36 int n,m,kase; 37 scanf("%d",&kase); 38 while(kase--) { 39 scanf("%d%d",&n,&m); 40 for(int i = 0; i < n; ++i) 41 scanf("%d",d+i); 42 build(0,n-1,1); 43 int low = 0,high = 0; 44 LL ret = 0; 45 while(low <= high && high < n) { 46 int minv = query(low,high,1,false); 47 int maxv = query(low,high,1,true); 48 if(maxv - minv < m) ret += high-low+1; 49 if(maxv - minv >= m) low++; 50 else high++; 51 } 52 cout<<ret<<endl; 53 } 54 return 0; 55 }