跳到正文

个人记录

123

heyechen约 3 分钟
原文

这是 2026年11月1日 存档的第 4 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年10月12日
收录
2026年10月12日
更新
2026年11月16日
篇幅
约 3 分钟

版本

  1. v6当前
  2. v5
  3. v4
  4. v3
更早的 2 个版本
  1. v2
  2. v1
C++
#include<bits/stdc++.h>
using namespace std;
int l[2000001],r[2000001],sl[2000001],sr[2000001],fl[2000001],fr[2000001];
long long a[2000001];
int main()
{
//	freopen("migrate.in","r",stdin);
//	freopen("migrate.out","w",stdout);
	int c,t,n,pl,pr,now;
	long long d,ans;
	scanf("%d%d",&c,&t);
	for(int i=1;i<=t;i++)
	{
		scanf("%d%lld",&n,&d);
		for(int j=1;j<=n;j++)
		{
			l[j]=r[j]=sl[j]=sr[j]=fl[j]=fr[j]=0;
			scanf("%lld",a+j);
		}
		now=1;
		for(int j=1;j<=n;j++)
		{
			while(a[j]-a[now]>d)
				now++;
			l[j]=now;
		}
		now=n;
		for(int j=n;j>=1;j--)
		{
			while(a[now]-a[j]>d)
				now--;
			r[j]=now;
		}
		now=1;
		for(int j=1;j<=n;j++)
		{
			while(now<j&&r[now]<=j)
				now++;
			sl[j]=j-now;
		}
		now=n;
		for(int j=n;j>=1;j--)
		{
			while(now>j&&l[now]>=j)
				now--;
			sr[j]=now-j;
		}
		for(int j=1;j<=n;j++)
			if(r[l[j]]<=j)
				fl[j]=j-l[j]-sl[j]+fl[l[j]];
			else
				fl[j]=0;
		for(int j=n;j>=1;j--)
			if(l[r[j]]>=j)
				fr[j]=r[j]-j-sr[j]+fr[r[j]];
			else
				fr[j]=0;
		ans=0;
		for(int j=2;j<=n-2;j++)
			if(r[j]>j+1&&l[j+1]<j)
			{
				pl=j+1-l[j+1]-sl[j+1];
				if(l[j]==l[j+1]&&r[l[j]]==j+1)
					pl+=fl[l[j]];
				pr=r[j]-j-sr[j];
				if(r[j]==r[j+1]&&l[r[j]]==j)
					pr+=fr[r[j]];
				ans+=1ll*pl*pr;
			}
		printf("%lld\n",ans);
	}
	return 0;
}