题目:http://noi.openjudge.cn/ch0111/01/
采用刘汝佳紫书P228程序8-6代码
解析:
以不降序列a[1..n]记录关键字。当x存在时返回它出现的第一个位置,如果不存在,返回这样一个下标,在此处插入x后,原序列仍然有序。记返回值为l。
举例说明,a[1..6]={1,2,2,6,6,10}。
若要查找的x=15,则返回插入位置下标7,因为7>6,输出a[6];
若要查找的x=6,则返回找到的下界位置4,输出a[4];
若要查找的x=5,则返回插入位置下标4,比较a[3]与a[4]与x的远近,输出a[4];
若要查找的x=-7,则返回插入位置下标1,输出a[1]。
AC代码:
#include<cstdio>
#include<iostream>
using namespace std;
int a[100000];/*不降序列*/
int main(){
int n=6,T,x;
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
cin>>T;
while(T--){
cin>>x;
int l=1,r=n+1;/*左闭右开区间*/
int mid;
while(l<r){/*lower_bound求下界位置*/
mid=(l+r)/2;
if(x<=a[mid])r=mid;
else if(x>a[mid])l=mid+1;
}
/*l的意义:当x存在时返回它出现的第一个位置,
如果不存在,返回这样一个下标,在此处插入x后,
原序列仍然有序*/
if(l>n)cout<<a[n]<<endl;
else if(l==1)cout<<a[1]<<endl;
else {
x=(2*x<=a[l-1]+a[l])?a[l-1]:a[l];
cout<<x<<endl;
}
}
return 0;
}