HDU - 5178 - Pairs (二分)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5178

题意

给定一个序列,找出满足 |x[b]−x[a]|≤.(a<b) 的<a,b>对数。

                                                                                                                                                                                               

题解

因为加了绝对值,所以可对数组内元素进行排序,然后进行二分查找,通过下标进行计数。

AC Code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool cmp(int x, int y)
{
    return x < y;
}
int a[100000+5];
int main()
{
    int T;
    cin>> T;
    while(T--)
    {
        int n, k;
        scanf("%d %d",&n,&k);
        memset(a,0,sizeof(a));
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
        }
        sort(a+1,a+1+n,cmp);
        ll ans = 0;
        int x;
        ll pos;
        for(int i=1; i<=n; i++)
        {
            x = a[i] + k;
            pos = upper_bound(a+1+i,a+1+n,x) - a;
//            printf("%d\n",pos);
            ans = ans + pos - i - 1;
        }
        printf("%lld\n",ans);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Alibaba_lhl/article/details/81268446