题目相关链接传送门:
1.https://blog.csdn.net/justidle/article/details/104593327?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-5&spm=1001.2101.3001.4242
2.https://vjudge.net/contest/378940#problem/C
我的AC代码:
#include<bits/stdc++.h> using namespace std; int lower_bound(int a[],int left,int right,int x)//检索数组中大于等于给定数x的最小项,返回其下标 { while(left<=right) { int mid=(left+right)/2; if(a[mid]>=x) right=mid-1; else left=mid+1; }//最后,left和right是重合着的 return left; } int main() { int n,m,i; cin>>n>>m; int a[n]; for(i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(i=0;i<m;i++) { int x; cin>>x; if(x<a[0]) cout<<a[0]<<endl; else if(x>a[n-1]) cout<<"-1 "; else { int pos=lower_bound(a,0,n-1,x); cout<<a[pos]<<endl; } } }
进一步扩展:
(1)二分查找-大于->右边界
#include<bits/stdc++.h> using namespace std; int upper_bound(int a[],int left,int right,int x)//检索数组中大于给定数x的最小项,返回其下标 { while(left<=right) { int mid=(left+right)/2; if(a[mid]>x) right=mid-1; else left=mid+1; }//最后,left和right是重合着的 return left; } int main() { int n,m,i; cin>>n>>m; int a[n]; for(i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(i=0;i<m;i++) { int x; cin>>x; if(x<a[0]) cout<<a[0]<<endl; else if(x>a[n-1]) cout<<"-1 "; else { int pos=upper_bound(a,0,n-1,x); cout<<a[pos]<<endl; } } }
(2)二分查找->大于等于——>左边界
#include<bits/stdc++.h> using namespace std; int lower_bound(int a[],int left,int right,int x)//检索数组中大于等于给定数x的最小项,返回其下标 { while(left<=right) { int mid=(left+right)/2; if(a[mid]>=x) right=mid-1; else left=mid+1; }//最后,left和right是重合着的 return left; } int main() { int n,m,i; cin>>n>>m; int a[n]; for(i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(i=0;i<m;i++) { int x; cin>>x; if(x<a[0]) cout<<a[0]<<endl; else if(x>a[n-1]) cout<<"-1 "; else { int pos=lower_bound(a,0,n-1,x); cout<<a[pos]<<endl; } } }
(3)二分查找——>是否存在等于某一特定值x的?
(4)二分查找——>等于特定值x的个数。
#include<bits/stdc++.h> using namespace std; int binary_search(int a[],int left,int right,int x)//检索数组中是否有某个数 { while(left<=right) { int mid=(left+right)/2; if(x==a[mid]) return mid; else if(x<a[mid]) right=mid-1; else left=mid+1; } return -1; } int main() { int n,m; cin>>n>>m; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(int i=0;i<m;i++) { int x; cin>>x; if(-1==binary_search(a,0,n-1,x)) cout<<"NO "; else cout<<"YES "; } return 0; }
#include<bits/stdc++.h> using namespace std; int lower_bound(int a[],int left,int right,int x)//检索数组中大于等于给定数x的最小项,返回其下标 { while(left<=right) { int mid=(left+right)/2; if(a[mid]>=x) right=mid-1; else left=mid+1; }//最后,left和right是重合着的 return left; } int upper_bound(int a[],int left,int right,int x)//检索数组中大于给定数x的最小项,返回其下标 { while(left<=right) { int mid=(left+right)/2; if(a[mid]>x) right=mid-1; else left=mid+1; }//最后,left和right是重合着的 return left; } int main() { int n,m,i; cin>>n>>m; int a[n]; for(i=0;i<n;i++) cin>>a[i]; sort(a,a+n); for(i=0;i<m;i++) { int x; cin>>x; int lower=lower_bound(a,0,n-1,x); int upper=upper_bound(a,0,n-1,x); cout<<upper-lower<<endl; } }