标签:
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)
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≤109). Next n lines contain an integer x[i](−109≤x[i]≤109), means the X coordinates.
For each case, output an integer means how many pairs<a,b> that |x[b]−x[a]|≤k.
2
5 5
-100 0 100 101 102
5 300
-100 0 100 101 102
3
10
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 #include<cmath> 7 using namespace std; 8 #define N 100006 9 #define ll long long 10 int n,k; 11 int a[N]; 12 int main() 13 { 14 int t; 15 scanf("%d",&t); 16 while(t--) 17 { 18 scanf("%d%d",&n,&k); 19 for(int i=0;i<n;i++) scanf("%d",&a[i]); 20 sort(a,a+n); 21 ll ans=0; 22 int tmp=0; 23 for(int i=0;i<n;i++) 24 { 25 while(abs(a[i]-a[tmp])<=k && tmp<n ) tmp++; 26 ans=ans+tmp-i-1; 27 } 28 printf("%I64d\n",ans); 29 } 30 return 0; 31 }
标签:
原文地址:http://www.cnblogs.com/UniqueColor/p/4743019.html