pairs
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3140 Accepted Submission(s): 1100
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.
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
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5178
题意:输入X轴上n个点的横坐标X[i](0<=i<n)和一个k,统计满足|X[b]-X[a]|<=k,(a<b)的(a,b)的对数。
解题思路:尺取法,这几天一直在找尺取法的题目在做,所以看到这道题直接就是用的尺取法,没想别的办法,因为取得是绝对值,所以a,b的顺序并不重要,直接排个序然后用尺取法做就好了。
AC代码:
#include<cstdio>
#include<algorithm>
using namespace std;
const int MAXN = 100000 + 10;//定义最大的点数
int n,k;
int x[MAXN];//点坐标数组
void solve()
{
int s,t;
long long cnt;
s=0,t=0,cnt=0;
for(s=0,t=0;s<n;s++) //尺取法,一步一步挪
{
while(x[t+1]-x[s]<=k && t+1<n) t++;//当差满足要求且下标不超过n时循环
cnt+=t-s;//更新结果。
}
printf("%lld\n",cnt);
}
int main(void)
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
{
scanf("%d",&x[i]);
}
sort(x,x+n);//因为是取绝对值,所以谁在前谁在后不影响结果
solve();
}
return 0;
}