题意:给你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}.