洛谷
找出有多少对奶牛 之间的距离小于d
upper_bound(a.begin(),a.end(),num)。这样可以在数组中找到第一个
大于
num的数的地址,如果不存在就返回
end。而由于是地址,就需要在最后减去
a。
lower_bound 找到第一个
大于等于
num的数的地址
#include <bits/stdc++.h>
#include <iostream>
#include<unordered_map>
#define x first
#define y second
#define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
typedef long long LL ;
typedef unsigned long long ULL ;
typedef pair<int,int> PII ;
typedef pair<LL,int> PLI ;
const int N = 2e6+10,M = 1000 * 100000 + 10 ,mod = 1000000007,INF1 = 0x3f3f3f3f;
const LL INF2 = 1e17;
int n,m;
int a[N];
inline void solve()
{
cin>>n>>m;
for(int i=1;i<=n;i ++ ) cin >> a[i];
sort(a+1,a+1+n);
int ans=0;
for(int i=1;i<=n;i ++ )
{
int k= upper_bound(a+i+1,a+n+1,a[i] + m) -a;
// a[k] > a[i] + m ,a[k-1] <= a[i] + m
k -- ;
ans += (k-i);
}
cout << ans <<endl;
}
signed main()
{
ios
int T=1;
// cin>>T;
while(T -- )
{
solve();
}
return 0;
}