Description
给定n个数,从中选出三个数,使得最大的那个减最小的那个的值小于等于d,问有多少种选法。
Input
第一行两个整数n,d(1 <= n <= 100,000,1 <= d <= 1000,000,000);
第二行n个整数满足abs(ai) <= 1,000,000,000。数据保证a单调递增。
Output
输出一个整数表示满足条件的选法。
Sample Input
4 3
1 2 3 4
Sample Output
4
Sample Input
4 2
-3 -2 -1 0
Sample Output
2
Sample Input
5 19
1 10 20 30 50
Sample Output
1
题解:遍历一遍即可。
代码如下:
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef long long ll;
using namespace std;
ll a[100005];
int main()
{
ll n,d;
while(~scanf("%lld%lld",&n,&d))
{
memset(a,0,sizeof(a));
for(int i=0; i<n; i++)
scanf("%lld",&a[i]);
ll l=0;
ll r=2;
ll sum=0;
while(l<n&&r<n)
{
if(r-l<2)
{
r++;
}
if(r==n)
break;
if(r-l>=2&&a[r]-a[l]<=d){
sum+=((r-l-1)*(r-l))/2;
r++;
}
if(a[r]-a[l]>d&&r-l>=2)
l++;
}
printf("%lld\n",sum);
}
return 0;
}