zoukankan      html  css  js  c++  java
  • Day8

    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.

    Input

    The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.

    It is guaranteed that the coordinates of the points in the input strictly increase.

    Output

    Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.

    Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

    Examples

    Input
    4 3
    1 2 3 4
    Output
    4
    Input
    4 2
    -3 -2 -1 0
    Output
    2
    Input
    5 19
    1 10 20 30 50
    Output
    1

    Note

    In the first sample any group of three points meets our conditions.

    In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.

    In the third sample only one group does: {1, 10, 20}.

    思路:维护双指针,每次右指针移一位,左指针到达最远距离,因为是递增序,两指针不减,统计答案时,每次定右指针,次数就是C(区间长度-1)(2),组合数

    typedef long long LL;
    
    const int maxm = 1e5+5;
    
    int buf[maxm];
    
    int main() {
        ios::sync_with_stdio(false), cin.tie(0);
        int n, d;
        cin >> n >> d;
        for(int i = 0; i < n; ++i)
            cin >> buf[i];
        LL ans = 0;
        int l = 0;
        for(int i = 2; i < n; ++i) {
            while(buf[i] - buf[l] > d) l++;
            ans += (LL)(i-l) * (i-l-1) / 2;
        }
        cout << ans << "
    ";
        return 0;
    }
    View Code
  • 相关阅读:
    JSE-1.1.4 内存屏障和CPU缓存
    Ajax
    R手册(Common)--R6 and S4
    掌握 小程序项目新建后的 初始代码 及 git远程管理(2)
    微信小程序 网课学习笔记 开发前的准备工作(1)
    vuex中action如何互相调用
    ajax请求时,请求路径自动拼上页面路径?
    10个免费的CDN
    java面向对象
    java中方法的递归调用
  • 原文地址:https://www.cnblogs.com/GRedComeT/p/12228179.html
Copyright © 2011-2022 走看看