题目描述
输入 n(n≤106) 个不超过 10^9 的单调不减的(就是后面的数字不小于前面的数字)非负整数 a1,a2,…,an,然后进行 m(m≤105) 次询问。对于每次询问,给出一个整数q(q≤109),要求输出这个数字在序列中第一次出现的编号,如果没有找到的话输出 -1 。
输入格式
第一行 2 个整数 n 和 m,表示数字个数和询问次数。
第二行 n 个整数,表示这些待查询的数字。
第三行 m 个整数,表示询问这些数字的编号,从 1 开始编号。
输出格式
m 个整数表示答案。
输入输出样例
输入 #1
11 3 1 3 3 3 5 7 9 11 13 15 15 1 3 6
输出 #1
1 2 -1
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-03-01 10:49:40
* @LastEditTime: 2022-03-01 10:57:14
*/
#include<bits/stdc++.h>
using namespace std;
int n,k;
int a[(int)1e6+10];
int b[(int)1e6+10];
int main()
{
while(cin>>n>>k){
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<k;i++)
cin>>b[i];
for(int i=0;i<k;i++){
int ans=lower_bound(a,a+n,b[i])-a;
//cout<<ans<<" ";
if(a[ans]==b[i])
cout<<ans+1<<" ";
else
cout<<"-1 ";
}
}
}
STL
自带的二分函数——upper_bound
和lower_bound
。二分查找一个数在数组中出现的位置。区别是
upper
返回第一个大于搜索数的位置,而lower
是第一个大于等于的数的位置。函数的用法:
lower_bound(a.begin(),a.end(),x)
返回第一个大于等于 xx 的数的地址。而由于是地址,在最后要 -a−a(也就是减去地址)。