[HDU](5178)pairs ---二分查找(查找)

pairs

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

解题新知:
①题意:
给你N个数分别为x0,x1,……xn-1,给你一个数K,询问你满足|xb-xa|<k   (a<b)情况有几种
②思路:题意很简单,如果暴力枚举,复杂度为O(n^2),肯定超时。那么我们可以用二分的思想,找到满足|xb-xa|的极限位置


AC代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
long long x[100005];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n,k;
        scanf("%d %d",&n,&k);
        for(int i=0;i<n;i++)
            scanf("%I64d",&x[i]);
        sort(x,x+n);
        long long mid;

        long long num=0;
        for(int i=0;i<n;i++)
        {
            long long l=i+1;
            long long r=n-1;
            while(l<=r)
            {
                mid=(l+r)/2;
                if(fabs(x[mid]-x[i])>k) //寻找比x[i]大的极限位置
                    r=mid-1;
                else
                    l=mid+1;
            }
            num=num+r-i;
        }
        cout<<num<<endl;
    }
    return 0;
}




posted @ 2017-08-22 19:18  WangMeow  阅读(154)  评论(0编辑  收藏  举报