Points on Line CodeForces - 251A (二分&单调队列)

\mathbb{C}题意:给你n,k和一个长度为n的数组,数组的值保证从小到大,问从中取出三个数,使得最大值减去最小值<=k,问有多少种取法

思路一:将数组遍历一遍,定义两个指针head和tail,如果满足条件就tail-head-1个数里面选出两个即组合数学的Cn2(我不会公式编辑器),然后累加起来就是答案了。网上说这是单调队列,但我更觉得这像暴力,只不过是可以保证O(n)的复杂度。

思路二:二分,相比上面的暴力法,就会快多了。

//单调栈暴力O(n)
#include<stdio.h>
typedef long long LL;
const int N=1e5+5;
LL ans,tmp;
int a[N],n,k;
int main()
{
    int head,tail;
    while(~scanf("%d%d",&n,&k))
    {
        ans=0;
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        head=0,tail=2;
        while(tail<n)
        {
            while(a[tail]-a[head]<=k&&tail<n)
            {
                tmp=tail-head;
                ans+=(tmp*(tmp-1))/2;//tmp个里面选两个
                tail++;//尾指针++
            }
            if(tail==n) break;
            while(a[tail]-a[head]>k) head++;//如果差>k,头指针++直到满足条件或找到末尾
        }
        printf("%lld\n",ans);
    }
}
//二分,不多说什么了,很好理解
#include<stdio.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int N=1e5+5;
int a[N],n,k;
LL tmp,ans;
int main()
{
    while(~scanf("%d%d",&n,&k))
    {
        ans=0;
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        for(int i=0;i<n-2;i++)
        {
            tmp=upper_bound(a+i,a+n,a[i]+k)-a-i-1;
            ans+=tmp*(tmp-1)/2;
        }
        printf("%lld\n",ans);
    }
}

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值