9.23

二分样题

题目描述
输入 n 个不超过 10 的单调不减的(就是后面的数字不小于前面的数字)非负整数 a
​,然后进行 m 次询问。对于每次询问,给出一个整数 q,要求输出这个数字在序列中第一次出现的编号,如果没有找到的话输出 −1 。

输入格式
第一行 2 个整数 n 和 m,表示数字个数和询问次数。

第二行 n 个整数,表示这些待查询的数字。

第三行 m 个整数,表示询问这些数字的编号,从 1 开始编号。

输出格式
输出一行,m 个整数,以空格隔开,表示答案。

输入
11 3
1 3 3 3 5 7 9 11 13 15 15
1 3 6
输出
1 2 -1

本题输入输出量较大,请使用较快的 IO 方式。

//最普通的二分

include

using namespace std;
const int N=1000010;
int a[N];
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>a[i];
int k;
while(m--)
{
cin>>k;
int l=0,r=n-1;
while(l<r)
{
int mid=l+r>>1;
if(a[mid]>=k)r=mid;
else l=mid+1;
}
if(a[l]==k)cout<<l+1<<" ";
else cout<<"-1"<<" ";
}
cout<<endl;
return 0;
}
//用到算法里面的upper_bound()和lower_bound()
//区别是 upper 返回第一个大于搜索数的位置,而 lower 是第一个大于等于的数的位置。

include

include

using namespace std;
const int N=1000010;
int a[N];
//快读的思路很好,比起直接cin>> 可以借鉴,以后可以一直用
int read(){//快读
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c'-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
x=x10+c-'0';
c=getchar();
}
return x
f;
}
int main()
{
int n,m;
n=read(),m=read();
for(int i=1;i<=n;i++)
a[i]=read();
while(m--)
{
int k=read();
//lower_bound(a.begin(),a.end(),x) 返回第一个大于等于 x 的数的地址。而由于是地址,在最后要 −a(也就是减去地址)。
int ans=lower_bound(a+1,a+n+1,k)-a;
if(a[ans]
k)cout<<ans<<" ";
else cout<<"-1"<<" ";
}
return 0;
}

posted @ 2025-09-27 18:34  苏楗轶  阅读(9)  评论(0)    收藏  举报