UVA 10474 - Where is the Marble?

Where is the Marble? 

Raju and Meena love to play with Marbles. They have got a lot of marbles with numbers written on them. At the beginning, Raju would place the marbles one after another in ascending order of the numbers written on them. Then Meena would ask Raju to find the first marble with a certain number. She would count 1...2...3. Raju gets one point for correct answer, and Meena gets the point if Raju fails. After some fixed number of trials the game ends and the player with maximum points wins. Today it's your chance to play as Raju. Being the smart kid, you'd be taking the favor of a computer. But don't underestimate Meena, she had written a program to keep track how much time you're taking to give all the answers. So now you have to write a program, which will help you in your role as Raju.

 

Input 

There can be multiple test cases. Total no of test cases is less than 65. Each test case consists begins with 2 integers: N the number of marbles and Q the number of queries Mina would make. The next N lines would contain the numbers written on the N marbles. These marble numbers will not come in any particular order. Following Q lines will have Q queries. Be assured, none of the input numbers are greater than 10000 and none of them are negative.

Input is terminated by a test case where N = 0 and Q = 0.

 

Output 

For each test case output the serial number of the case.

For each of the queries, print one line of output. The format of this line will depend upon whether or not the query number is written upon any of the marbles. The two different formats are described below:

 

  • `x found at y', if the first marble with number x was found at position y. Positions are numbered 1, 2,...,N.
  • `x not found', if the marble with number x is not present.

Look at the output for sample input for details.

 

Sample Input 

4 1

2

3

5

1

5

5 2

1

3

3

3

1

2

3

0 0

 

Sample Output 

CASE# 1:

5 found at 4

CASE# 2:

2 not found

3 found at 3

 1 // UVa10474 Where is the Marble?

 2 // Rujia Liu

 3 // rev 2. fixed bug reported by EndlessCheng

 4 // 代码由刘汝佳提供,我是在我的水平下,加以注释,学习大神的思想

 5 #include<cstdio>

 6 #include<algorithm>//使用sort和lower_bound

 7 using namespace std;

 8 

 9 const int maxn = 10000;

10 

11 int main() {

12   int n, q, x, a[maxn], kase = 0;

13   while(scanf("%d%d", &n, &q) == 2 && n) {

14     printf("CASE# %d:\n", ++kase);

15     for(int i = 0; i < n; i++) scanf("%d", &a[i]);

16     sort(a, a+n); // 排序

17     while(q--) {

18       scanf("%d", &x);

19       int p = lower_bound(a, a+n, x) - a; // 在已排序数组a中寻找x

20       if(p < n && a[p] == x) printf("%d found at %d\n", x, p+1);

21       else printf("%d not found\n", x);

22     }

23   }

24   return 0;

25 }
void sort( iterator start, iterator end ); 
传递你要排序的串的头指针(数组第一个元素的指针)与数组最后元素的下一个位置
排序结果是升序。
lower_bound 用法和上面类似,返回 大于或等于x的第一个位置。
(我认为是 返回的东西 减去 头指针 等于数组的下标,可能还有其他用法,我先这样用)

你可能感兴趣的:(where)