The STL contains four different binary search algorithms ,binary_search lower_bound upper_bound equal_range. Their scopes are already sorted a good array.
★ Binary_search tried to find the element value in the sorted [first, last]. Returns true if it is found, or false if it does not return a lookup location.
★Iterator lower_bound(const key_type &key): Returns an iterator that points to the first element of the key value >= key . ★Iterator upper_bound(const key_type &key): Returns an iterator that points to the first element of the key, value > key. HDU 5178 Pairs
Problem Description John had n points on the X axis, and their coordinates is (x[i],0), (i=0,1,2,..., n−1). He wants to know what 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 is begins with the integers n,k (1≤n≤100000,1≤k≤109).
Next n lines contain an integer x[i] (−109≤x[i]≤109), means the x coordinates.
Output for each case, output a 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 Bestcoder Round #31
Reference Code one (using binary lookup function Upper_bound)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
# Include <climits>
#define EPS 1e-10
using namespace std;
typedef long long LL;
const int Inf=int_max;
const int MAXN = 1E5+10;
int N,K,A[MAXN];
int main ()
{
// freopen ("Input.txt", "R", stdin);
int t;cin>>t;
while (t--) {
cin>>n>>k;
for (int i=0;i<n;i++) scanf ("%d", a+i);
Sort (a,a+n);
ll Ans=0;
for (int i=0;i<n;i++) {
ans+=upper_bound (a,a+n,a[i]+k)-a-1-i;//upper_bound return value-A gets the number of elements <=a[i]+k, Again-1 is to correct the initial position starting from 0, and the last minus I get is the pair number with I
}
printf ("%lld\n", ans);
}
return 0;
}
Reference Code II (handwritten binary lookup function)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
# Include <climits>
#define EPS 1e-10
using namespace std;
typedef long long LL;
const int Inf=int_max;
const int MAXN = 1E5+10;
int N,K,A[MAXN];
ll ans;
int binary_search (int num,int pos) {
int low=pos+1,high=n-1,mid,res=0;
while (Low<=high) {
mid= (low+high) >>1;
if (a[mid]-num>k) high=mid-1;
else{
res=mid-pos;//directly get the number of pair, or else to determine whether there is no result to deal with the
low=mid+1;}
}
Return res;//No then returns an initial value
of 0}
int main ()
{
//Freopen ("Input.txt", "R", stdin);
int t;cin>>t;
while (t--) {
scanf ("%d%d", &n,&k);
for (int i=0;i<n;i++) scanf ("%d", a+i);
Sort (a,a+n);
ans=0;
for (int i=0;i<n;i++) {
ans+=binary_search (a[i],i);//cumulative Process
}
printf ("%lld\n", ans);
}
return 0;
}