P2249 【深基13.例1】查找 模板
题目大意
给定n个数字然后给m个查找,每次查找给定数字x的位置。
思路
二分板子,找出最左边的那个数字就行。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int a[N];
int n;
int find(int x) {
int l = 0, r = n;
while (l < r) {
int mid = l + r >> 1;
if (a[mid] >= x) r = mid;
else l = mid + 1;
}
if (a[l] == x) return l + 1;
else return -1;
}
int main() {
int k;
cin >> n >> k;
for (int i = 0; i < n; i++) scanf("%d",a + i);
while (k--) {
int x;
cin >> x;
cout << find(x) << " ";
}
return 0;
}
备注
整数二分会有两个二分查找的模板,这是其中一个。