Problem Description
John has n points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,…,n−1). He wants to know how many pairs<a,b> that |x[b]−x[a]|≤k.(a<b)
Input
The first line contains a single integer T (about 5), indicating the number of cases.
Each test case begins with two integers n,k(1≤n≤100000,1≤k≤10^9).
Next n lines contain an integer x[i](−10^9≤x[i]≤10^9), means the X coordinates.
Output
For each case, output an integer means how many pairs<a,b> that |x[b]−x[a]|≤k.
Sample Input
2 5 5 -100 0 100 101 102 5 300 -100 0 100 101 102
Sample Output
3 10
题意:
首先是多组样例,对于每组样例,给你一个n和k,代表数组中有n个数(n个数没有顺序),设数组为x数组,问你存在多少对坐标<a,b>,使得x[b] - x[a] <= k。范围:1≤n≤10^5,1≤k≤10^9
思路:
首先将x数组排序,然后for循环1~n-1枚举x[a],然后二分查找满足条件的x[b]即可(时间复杂度n(logn))
代码:
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
int n,k;
int T;
cin>>T;
while(T--)
{
cin>>n>>k;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+1+n);
LL ans=0;
for(int i=1;i<n;i++)
{
int t=lower_bound(a+1,a+n+1,a[i]+k)-a;
if(a[t]-a[i]==k)
ans+=t-i;
else ans+=t-i-1;
}
cout<<ans<<endl;
}
return 0;
}