【深基13.例1】查找
题目描述
输入 n n n 个不超过 1 0 9 10^9 109 的单调不减的(就是后面的数字不小于前面的数字)非负整数 a 1 , a 2 , … , a n a_1,a_2,\dots,a_{n} a1,a2,…,an,然后进行 m m m 次询问。对于每次询问,给出一个整数 q q q,要求输出这个数字在序列中第一次出现的编号,如果没有找到的话输出 − 1 -1 −1 。
输入格式
第一行 2 2 2 个整数 n n n 和 m m m,表示数字个数和询问次数。
第二行 n n n 个整数,表示这些待查询的数字。
第三行 m m m 个整数,表示询问这些数字的编号,从 1 1 1 开始编号。
输出格式
输出一行, m m m 个整数,以空格隔开,表示答案。
样例 #1
样例输入 #1
11 3
1 3 3 3 5 7 9 11 13 15 15
1 3 6
样例输出 #1
1 2 -1
提示
数据保证, 1 ≤ n ≤ 1 0 6 1 \leq n \leq 10^6 1≤n≤106, 0 ≤ a i , q ≤ 1 0 9 0 \leq a_i,q \leq 10^9 0≤ai,q≤109, 1 ≤ m ≤ 1 0 5 1 \leq m \leq 10^5 1≤m≤105
本题输入输出量较大,请使用较快的 IO 方式。
思路
数据量很大,需要优化读入。lower_bound通过二分查找,返回第一个大于等于某个数的元素的指针。如果指针解引用正好是要找的数,则该指针和向量开头的差值加一为这个数字在序列中第一次出现的编号。如果用lower_bound返回的指针为向量结尾,或对其解引用的值不为查询的值,则没有找到,返回-1。
AC代码
#include <iostream>
#include <vector>
#include <algorithm>
#define AUTHOR "HEX9CF"
using namespace std;
int read(){
char ch;
int x = 0;
while((ch < '0' || ch > '9')){
ch = getchar();
}
while(!(ch < '0' || ch > '9')){
x = x * 10 + ch - '0';
ch = getchar();
}
return x;
}
int main(){
int n, m;
vector<int> a;
n = read();
m = read();
for(int i = 0; i < n; i++){
a.push_back(read());
}
for(int i = 0; i < m; i++){
if(i){
putchar(' ');
}
int t = read();
vector<int>::iterator lb = lower_bound(a.begin(), a.end(), t);
if(lb == a.end() || *lb != t){
cout << -1;
}else{
cout << lb - a.begin() + 1;
}
}
return 0;
}