AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 1. Elementary Problem Solving ::Sorting/Searching
Description
找弹珠。
每个弹珠都有一个数字(可重复), 且按数字大小给弹珠排序。
询问一个数字, 要求输出该数字在弹珠中出现的最小位置。
Type
Sorting/Searching
Analysis
给弹珠排序一下, 然后二分查找并输出即可。
Solution
// UVaOJ 10474
// Where is the Marble?
// by A Code Rabbit
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAXN = 10002;
int n, q;
int marbles[MAXN];
int main() {
int cnt_case = 0;
while (scanf("%d%d", &n, &q) && (n || q)) {
for (int i = 0; i < n; i++)
scanf("%d", &marbles[i]);
sort(marbles, marbles + n);
printf("CASE# %d:\n", ++cnt_case);
for (int i = 0; i < q; i++) {
int num;
scanf("%d", &num);
if (binary_search(marbles, marbles + n, num))
printf("%d found at %d\n",
num, lower_bound(marbles, marbles + n, num) - marbles + 1);
else
printf("%d not found\n", num);
}
}
return 0;
}