您的位置:首页 > 其它

二分查找

2015-07-22 10:33 417 查看
最近太懒,懒得写博客,毕竟有大神的博客可以参考,也就不想自己动手了。

昨天刚刚比完多校,被虐死了。

1002一个二分查找居然debug了许久,所以今天特地来巩固巩固二分查找。

stl自带的binary_search、lower_bound和upper_bound的查询区间都是
左闭右开的!!!

然后附上自己整理出来的这三个函数,以后不要再入坑了!

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <sstream>
using namespace std;

#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1

typedef long long LL;
const double pi=4.0*atan(1.0);
const int MAXN=1000000;

int a[50];

int lower(int x,int y,int k)
{
int m;
while(x<y)
{
m=(x+y)/2;
if(a[m]>=k)			//改成<=可以求递减序列
y=m;
else
x=m+1;
}
return x;
}

int upper(int x,int y,int k)
{
int m;
while(x<y)
{
m=(x+y)/2;
if(a[m]<=k)		//改成>=可以求递减序列
x=m+1;
else
y=m;
}
return x;
}

int bsearch(int x,int y,int k)
{
int m;
while(x<y)
{
m=(x+y)/2;
if(a[m]==k)
return m;
else if(a[m]>k)
y=m;
else
x=m+1;

}
return -1;
}
int main()
{
int i,j,k;
int n;
int m,o;
int x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%d",a+i);
for(i=0;i<m;i++)
{
scanf("%d",&o);
printf("%d\n",upper(1,n+1,o));

}

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: