CodeForces 251A The Distance

6 篇文章 0 订阅
A - The Distance
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

Description

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 cincout streams or the %I64dspecifier.

Sample Input

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

Hint

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


排序后枚举第一个点,下表记为a,然后二分这点之后所有点找出差不超过d的最大位置,下标记为b,那么以a为起点共有

C(2,b-a)种取法。最后累加所有a即可。


#include <iostream>

using namespace std;
long long n,d,ans=0;
long long a[101000];
long long bse(long long x,long long nn){
   long long  l=x,r=n,m,i,j;
   m=(l+r)/2;
   if (x==n) {
     if (a[x]-a[nn]>d) return x-1;
     else return n;
   }
   if (a[r]-a[nn]<=d) return r;
   if (a[l]-a[nn]>d) return x-1;
   while (l<r){
     if (a[m]-a[nn]>d) r=m-1;
     else l=m;
     if (a[r]-a[nn]>d) r=r-1;
     m=(l+r)/2;
     if (a[r]-a[nn]<=d) return r;
   }
   return m;
}
int main()
{
    cin>>n>>d;
    long long i;
    for (i=1;i<=n;i++) cin>>a[i];
    ans=0;
    for (i=1;i<n;i++) {
      long long t=bse(i+1,i)-i;
      ans=ans+t*(t-1)/2;
    }
    cout<<ans<<endl;
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值