hdu 5178(二分-lower_bound,upper_bound)

pairs

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2037    Accepted Submission(s): 732


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
 
Source
 
Recommend
hujie   |   We have carefully selected several similar problems for you:  5733 5732 5731 5730 5729 
 
 
题意:给出一个含有n个元素的数组 ,要求 |a[j]-a[i]|<=k && i<j 问在这个序列中有多少个二元组满足这个条件??
题解:将两个条件化一下可以得到 1, a[i] - k <= a[j] <= a[i] + k  2, i < j
所以我们可以利用 c++ 提供的工具 lower_bound 和 upper_bound
1.lower_bound 返回第一个大于等于当前元素的第一个数的下标.
2.upper_bound 返回第一个小于等于当前元素的第一个数的下标.
所以用这个可以分别找到大于等于 a[i] - k 和小于等于 a[i]+k 的第一个位置.
然后判断一下下界是否大于 i ,如果不是则 l = i+1
判断一下上界是否大于 i ,如果不是直接continue。最后,计数即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long LL;
const int N = 100005;
LL a[N];
int main()
{
    int tcase;
    int n;
    LL k;
    scanf("%d",&tcase);
    while(tcase--){
        scanf("%d%lld",&n,&k);
        for(int i=1;i<=n;i++){
            scanf("%lld",&a[i]);
        }
        sort(a+1,a+n+1);
        LL cnt = 0;
        for(int i=1;i<=n;i++){
            int l = lower_bound(a+1,a+1+n,a[i]-k)-a;
            int r = upper_bound(a+1,a+1+n,a[i]+k)-a;
            if(l<=i) l = i+1;
            if(r>=i){
                cnt+=(r-l);
            }
        }
        printf("%lld
",cnt);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/liyinggang/p/5686034.html