UVA 10474 Where is the Marble? 暴力|STL

点击打开题目链接

给一组数,排序,查找。

方法一:暴力 380ms

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN = 10000 + 10;
int num[MAXN];

int main()
{

    int n, m, kase = 1;
    while (~scanf("%d%d", &n, &m))
    {
        if (n == 0) break;
        for (int i = 0; i < n; i++) scanf("%d", &num[i]);
        sort(num, num + n);             //排序
        printf("CASE# %d:\n", kase++);
        for (int i = 0; i < m; i++)
        {
            int x;
            scanf("%d", &x);
            int ok = 0;
            for (int k = 0; k < n; k++)     //暴力查找
                if(num[k] == x)
                {
                    ok = 1;
                    printf("%d found at %d\n", x, k + 1);
                    break;
                }
            if (ok == 0)
            {
                printf("%d not found\n", x);
            }
        }
    }
    return 0;
}

方法二:STL,二分查找 50ms

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN = 10000 + 10;
int num[MAXN];

int main()
{
    int n, m, kase = 1;
    while (~scanf("%d%d", &n, &m))
    {
        if (n == 0) break;
        for (int i = 0; i < n; i++) scanf("%d", &num[i]);
        sort(num, num + n);
        printf("CASE# %d:\n", kase++);
        for (int i = 0; i < m; i++)
        {
            int x;
            scanf("%d", &x);
            int k = lower_bound(num, num + n, x) - num; //二分查找
            if (x == num[k])
            {
                printf("%d found at %d\n", x, k + 1);
            }
            else
            {
                printf("%d not found\n", x);
            }
        }
    }
    return 0;
}


你可能感兴趣的:(ACM,STL)