题目描述
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn’t exceed d.
Note that the order of the points inside the group of three chosen points doesn’t matter.
大意:给你一个长度为 n 的递增集合,现在要在集合中取出 3 个数,使得最大数与最小数的差值小于 d,问有多少种取法。
分析
直接用尺取法更新每一个满足这样的条件的区间里面的点的个数,然后用一些排列组合的知识更新答案就好。时间复杂度O(n)。
代码
#include <cstdio>
using namespace std;
const int N = 1e5 + 10;
int n, d;
int a[N];
int main() {
scanf("%d%d", &n, &d);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
}
int l = 0, r = 1, cnt = 0;
long long ans = 0;
while (l < n - 2){
while (a[r] <= a[l] + d && r < n){
r++;
}
cnt = r - l - 1;
if (cnt >= 2);
ans += 1LL * cnt* (cnt - 1) / 2;
cnt = 0;
l++;
}
printf("%lld\n", ans);
return 0;
}