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≤109). Next n lines contain an integer x[i](−109≤x[i]≤109), 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
Source
题意:给定一个数组,求有多少对<a,b>使得|x[b]−x[a]|≤k.(a<b)
思路:1、这道题最重要的就是要解决超时这个问题,否则按暴力肯定是超时的。
2、解决超时,这里有种方法。
先将这个数组从小到大排序,然后i从0开始,tmp从0开始判断,如果值小于等于k的话,tmp++,直到>k停止,
ans加上该值。下一次,i+1,之前的i和k可以,那么和i+1更可以,所有k继续向后跑,如此复杂度大大减少。
具体看代码
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 }
时间: 2024-10-23 09:44:05