HDU - 5178 - pairs(二分)

该博客介绍了如何利用二分查找算法解决HDU在线判题系统中的题目5178 - pairs。题目要求在X轴上的n个点中找出满足特定距离限制的点对数量。博客提供了详细的题意解析、输入输出说明、思路分析以及代码实现,代码主要采用排序加二分查找的方法,实现了时间复杂度为n(logn)的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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≤10^9).
Next n lines contain an integer x[i](−10^9≤x[i]≤10^9), 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

 

题意:

首先是多组样例,对于每组样例,给你一个n和k,代表数组中有n个数(n个数没有顺序),设数组为x数组,问你存在多少对坐标<a,b>,使得x[b] - x[a] <= k。范围:1≤n≤10^5,1≤k≤10^9

 

思路:

首先将x数组排序,然后for循环1~n-1枚举x[a],然后二分查找满足条件的x[b]即可(时间复杂度n(logn))

 

代码:

#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
    int n,k;
    int T;
    cin>>T;
    while(T--)
    {
      cin>>n>>k;
      for(int i=1;i<=n;i++)
         cin>>a[i];
      sort(a+1,a+1+n);
      LL ans=0;
      for(int i=1;i<n;i++)
      {
         int t=lower_bound(a+1,a+n+1,a[i]+k)-a;
         if(a[t]-a[i]==k)
            ans+=t-i;
         else ans+=t-i-1;
      }
      cout<<ans<<endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值