UVA10474 大理石在哪儿 Where is the Marble?

简介: UVA10474 大理石在哪儿 Where is the Marble?

题意翻译

现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回 答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上 写着x。排序后的大理石从左到右编号为1~N。

输入样例

4 1

2

3

5

1

5

5 2

1

3

3

3

1

2

3

0 0

输出样例

CASE# 1:

5 found at 4

CASE# 2:

2 not found

3 found at 3

代码

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int n,m,q,cas;
int arr[10000 + 10];
int main() {
  while (cin >> n >> m && n) {
    cout << "CASE# " << ++cas << ":" << endl;
    memset(arr, 0, sizeof(arr));
    for (int i = 0; i < n; i++) {
      cin >> arr[i];
    }
    sort(arr, arr + n);
    while (m--) {//
      cin >> q;
      int index = lower_bound(arr, arr + n, q)-arr;//返回元素的索引
      if (arr[index] == q) {//这里必须这样写,不能直接判断是否索引是0  但可以换成 index != n
        cout << q << " " << "found at " << index + 1 << endl;
      }
      else {
        cout << q << " " << "not found" << endl;
      }
    }
  }
  return 0;
}

注:lower_bound() 函数,返回小于等于key的第一个元素,返回值是元素的索引。当没有找到时返回最后最后一个元素后面的位置的指针。

相关文章
|
9月前
UVa11876 - N + NOD (N)
UVa11876 - N + NOD (N)
39 0
|
9月前
UVa389 - Basically Speaking
UVa389 - Basically Speaking
24 0
UVA439-骑士的移动 Knight Moves(BFS)
UVA439-骑士的移动 Knight Moves(BFS)
UVA439-骑士的移动 Knight Moves(BFS)
POJ-2488,A Knight's Journey(DFS)
POJ-2488,A Knight's Journey(DFS)
|
存储 算法 测试技术
UVA - 10474 Where is the Marble
Raju and Meena love to play with Marbles. They have got a lot of marbles with numbers written on them.
1364 0