标签:
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 cin, cout streams or the %I64dspecifier.
Sample Input
Input4 3
1 2 3 4Output4Input4 2
-3 -2 -1 0Output2Input5 19
1 10 20 30 50Output1
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}.
题意:给定一个递增的数列,求出从这个数列中取出3个数,最大值与最小值的差值小于等于k的有多少种。
思路:有点递推的感觉,每加进来一个数,只考虑这个数的贡献,例如,加进来第5个数的时候,假设前面四个数都符合要求,那么5的贡献就是从前面4个数当中取出两个来的总数,所以就是C 4 2, 这是个组合数。所以考虑每一个数,把每个数的组合数加起来就是了
代码一(单调队列);
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 100010; int a[maxn]; int q[maxn]; int main() { int n, d; scanf("%d %d", &n, &d); ll ans = 0; int front = 1, tail = 0; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); q[++tail] = a[i]; while (tail >= front && q[front] < a[i] - d) front++; int j = tail - front; ans += (ll)j * (j - 1) / 2;//C n 2 } printf("%I64d\n", ans); return 0; }
代码二(二分):
#include <cstdio> #include <iostream> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 100010; int a[maxn]; int main() { int n, d; scanf("%d %d", &n, &d); ll ans = 0; for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 1; i < n; i++) { int j = i - (lower_bound(a, a + i, a[i] - d) - a); ans += (ll)j * (j - 1) / 2; } printf("%I64d\n", ans); return 0; }
codeforces 251A Points on Line(二分or单调队列)
标签:
原文地址:http://www.cnblogs.com/Howe-Young/p/4800222.html