STL
程序员文章站
2022-03-23 11:24:01
...
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
#define N 200005
int stmax[N][20],stmin[N][20],mn[N];
int a[N];
int t,q,n;
int x,y;
void init()
{
mn[0]=-1;
for (int i=1;i<=n;i++)
{
mn[i]=((i & (i-1))==0) ? mn[i-1]+1 : mn[i-1];
stmax[i][0]=stmin[i][0]=a[i];
}
for (int j=1;j<=mn[n];j++)
for (int i=1;i+(1<<j)-1<=n;i++)
{
stmax[i][j]=max(stmax[i][j-1],stmax[i+(1<<(j-1))][j-1]);
stmin[i][j]=min(stmin[i][j-1],stmin[i+(1<<(j-1))][j-1]);
}
}
int rmq_max(int L,int R)
{
int k=mn[R-L+1];
return max(stmax[L][k],stmax[R-(1<<k)+1][k]);
}
int rmq_min(int L,int R)
{
int k=mn[R-L+1];
return min(stmin[L][k],stmin[R-(1<<k)+1][k]);
}
int kkk;
int main()
{
while (~scanf("%d%d",&n,&kkk))
{
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
init();
int ans=0;
for(int i=1;i<=n;i++)
{
int low=i;
int hign=n;
int mid;
while(low<=hign)
{
mid=(low+hign)/2;
int tmax=rmq_max(i,mid);
int tmin=rmq_min(i,mid);
int ttt=tmax-tmin;
if(ttt<=kkk)
{
low=mid+1;
}
else
{
hign=mid-1;
}
}
//cout<<"mid "<<mid<<endl;
ans+=(low-i);
}
cout<<ans<<endl;
}
return 0;
}