HDU 5178 pairs

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,,n1) . 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(1n100000,1k109) .
Next  n  lines contain an integer  x[i](109x[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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值