STL包含四种不同的二分查找算法,binary_search lower_bound upper_bound equal_range.他们的作用域是已经排序好的的数组。
★binary_search试图在已排序的[first, last)中寻找元素value。如果找到它会返回true,否则返回false,它不返回查找位置。
★iterator
lower_bound( const key_type &key ): 返回一个迭代器,指向键值>=
key的第一个元素。
★iterator
upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。
hdu 5178 pairs
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≤109).
Next n lines
contain an integer x[i](?109≤x[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
参考代码一(使用二分查找函数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返回值-a得到<=a[i]+k的元素个数,再-1是为了矫正初始位置从0开始,最后减去i得到的是与i的pair个数 } printf("%lld\n",ans); } return 0; }
参考代码二(手写二分查找函数)
#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;//直接得到pair个数,否则还要判断有没有结果再处理 low=mid+1; } } return res;//没有则返回初始值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);//累加过程 } printf("%lld\n",ans); } return 0; }