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
  • 相关阅读:
    MySQL学习笔记(12):触发器
    MySQL学习笔记(11):存储过程和函数
    MySQL学习笔记(10):视图
    MySQL学习笔记(9):索引
    MySQL学习笔记(8):字符集
    MySQL学习笔记(7):存储引擎
    MySQL学习笔记(6):常用函数
    MySQL学习笔记(5):运算符
    MySQL学习笔记(4):数据类型
    MySQL学习笔记(3):SQL
  • 原文地址:https://www.cnblogs.com/GRedComeT/p/12228179.html
Copyright © 2011-2022 走看看