UVA10474 Where is the Marble?

问题链接:UVA10474 Where is the Marble?

题意简述:输入n个整数,代表大理石编号;再输入q个数(编号),问是否有这个编号的大理石,位置在哪里?

这个问题用C++语言编写程序,主要是为了练习使用STL的功能。

程序中,使用了算法库(algorithm)中的两个函数;使用sort()函数用于对数据排序,该函数的参数比C语言的同类函数简单,程序更加易于书写;使用函数lower_bound()查找元素,简单方便。


AC的C++语言程序如下:

/* UVA10474 Where is the Marble? */

#include <iostream>
#include <algorithm>

using namespace std;

#define MAXN 11000

int marble[MAXN];

int main()
{
    int n, q, caseno=0, val;

    while(scanf("%d%d", &n, &q) != EOF) {
        if(n == 0 && q == 0)
            break;

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

        sort(marble, marble + n);

        printf("CASE# %d:
", ++caseno);
        while(q--) {
            scanf("%d", &val);
            int no = lower_bound(marble, marble + n, val) - marble;
            if(marble[no] == val)
                printf("%d found at %d
", val, no + 1);
            else
                printf("%d not found
", val);
        }
    }

    return 0;
}


原文地址:https://www.cnblogs.com/tigerisland/p/7564503.html