John has nn points on the X axis, and their coordinates are (x[i],0),(i=0,1,2,…,n−1)(x[i],0),(i=0,1,2,…,n−1). He wants to know how many pairs<a,b><a,b> that |x[b]−x[a]|≤k.(a<b)
Input
The first line contains a single integer TT (about 5), indicating the number of cases.
Each test case begins with two integers n,k(1≤n≤100000,1≤k≤109)n,k(1≤n≤100000,1≤k≤109).
Next nn lines contain an integer x[i](−109≤x[i]≤109)x[i](−109≤x[i]≤109), means the X coordinates.
Output
For each case, output an integer means how many pairs<a,b><a,b> that |x[b]−x[a]|≤k|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
题目大意:x轴上有n个坐标,求出所有满足满足条件的两个点,使x[b]-x[a]<=k,(a,b);
解题思路:用二分来解,二分之前先排下序,这样就不用考虑绝对值的问题了,从前往后遍历,对于每一个a[i],二分一下,求出后面有多少个满足题意的点.
注意:结果会很大,int会超。。。。。。
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+100;
ll n,k,a[maxn];
bool solve(ll a,ll b)
{
if(b-a<=k)
return true;
else
return false;
}
ll bin(ll term,ll L,ll R)
{
while(L<=R)
{
ll mid=(L+R)/2;
if(solve(a[term],a[mid]))//当前mid满足,使L后移,这样最后L的结果即是满足条件的最后一个数的下一位
L=mid+1;
else
R=mid-1;
}
return L-term-1;//要减1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld%lld",&n,&k);
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i]);
}
sort(a,a+n);
ll sum=0;//结果很大long long 定义
for(ll i=0;i<n;i++)
{
sum+=bin(i,i,n-1);//二分
}
cout<<sum<<endl;
}
return 0;
}