跳到正文

题解

AT_abc444_e

Gaochenxi103_QAQ约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年2月8日
收录
2026年2月8日
更新
2026年11月13日
篇幅
约 2 分钟

版本

  1. v1当前

做法

考虑类似双指针的思路,从小到大枚举左端点。然后维护右端点。因为当 (l,r)(l,r) 是一对合法点对,∀l≤l′≤r′≤r,(l′,r′)\forall l\le l'\le r'\le r,(l',r') 也是一对合法点对。

那么对于一个 ll,它可以继承 l−1l-1 的 rr。并再尽可能的向后延伸,找到最大的可以满足的 rr。

每次判断 r+1r+1 是否可行,只需要用multiset维护当前 l,rl,r 区间的所有元素;二分找到第一个大于等于它和第一个小于等于它的数,然后判断两者是否都满足与 ar+1a_{r+1} 的差值大于等于 DD 即可。

赛时代码

Accepted code
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=4e5+10;
int n,d,a[N],ans=0;
multiset<int>p;
bool check(int x)
{
	auto mid=p.lower_bound(x);
	auto midd=p.lower_bound(x-d+1);
	if(mid!=p.end() && abs(*mid-x)<d)return false;
	if(midd!=p.end() && abs(*midd-x)<d)return false;
	return true;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>d;
	for(int i=1;i<=n;i++)cin>>a[i];
	int r=0;
	for(int l=1;l<=n;l++)
	{
		if(r<l)
		{
			r=l;
			p.clear();
			p.insert(a[l]);
		}
		else
		{
			if(l!=1)p.erase(p.find(a[l-1]));
		}
		while(r<n && check(a[r+1]))
		{
			r++;
			p.insert(a[r]);
		}
//		cout<<l<<" "<<r<<"\n";
		ans+=(r-l+1);
	}
	cout<<ans;
	return 0;
}
原文