【CF251A】Points on Line O(n)复杂度

Points on Line

题目描述

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值