标签:
Light oj上的某水题,用来总结二分查找板子
之前鲁二分查找总是要自己YY,DEbug半天,因为没有总结板子
此板子适应查找下界,方便判断查找元素是否存在,没有什么可挑剔的了
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn=100008; int a[maxn]; int n; int bs(int x) { int left=1,right=n; while(left<=right) { int mid=(left+right)>>1; if(a[mid]==x) right=mid-1; else if(a[mid]>x) right=mid-1; else left=mid+1; } return left+1; } int main() { int i,j,t,q,x,y; scanf("%d",&t); int cas=1; while(t--) { scanf("%d%d",&n,&q); for(i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+1+n); printf("Case %d:\n",cas++); while(q--) { scanf("%d%d",&x,&y); int left=bs(x); int right=bs(y+1); printf("%d\n",right-left); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/bitch1319453/p/4924422.html