您的位置:首页 > 大数据 > 人工智能

hdu 5178 pairs (线性探查问题)

2015-08-19 18:11 411 查看
[align=left]Problem Description[/align]

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−x[a]|≤k.(a<b)


[align=left][b]Input
[/align]

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.


[align=left]Output[/align]

For each case, output an integer means how many pairs<a,b> that |x−x[a]|≤k.


[align=left][b]Sample Input
[/align]

2
5 5
-100 0 100 101 102
5 300
-100 0 100 101 102


[align=left]Sample Output[/align]

3
10


[align=left]Source[/align]
BestCoder Round #31
题意:给定一个数组,求有多少对<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继续向后跑,如此复杂度大大减少。
具体看代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stdlib.h>
#include<cmath>
using namespace std;
#define N 100006
#define ll long long
int n,k;
int a
;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
ll ans=0;
int tmp=0;
for(int i=0;i<n;i++)
{
while(abs(a[i]-a[tmp])<=k && tmp<n ) tmp++;
ans=ans+tmp-i-1;
}
printf("%I64d\n",ans);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: