1. 程式人生 > >251A Points on Lines

251A Points on Lines

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}.
#include <iostream>
#include <cstdio>
#include <algorithm>
typedef long long ll;
using namespace std;
ll a[100005];
ll C(ll x,ll y){
    if(x<y) return 0;
    ll sum=1;
    for(int i=x,j=1;j<=y;i--,j++)
        sum=sum*i/j;
    return sum;
}
int main(){
    ll n,d,ans;
    while(cin>>n>>d){
        for(int i=1;i<=n;i++) cin>>a[i];
        ans=0;
        for(int i=1;i<=n-2;i++){
            ll tep=a[i]+d,tmp;
            int l=i,r=n,mid;
            while(l<=r){
                mid=(l+r)>>1;
                if(a[mid]<=tep) l=mid+1,tmp=mid;
                else  r=mid-1;
            }
            ans+=C(tmp-i,2);
        }
        cout<<ans<<endl;
    }
    return 0;
}