Uva10474 - Where is the Marble?

 

两种解法:

1.计数排序

//计数排序
#include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
const int maxn=10001;
int v[maxn], s[maxn];

int main() {
    int N, Q;
    int Kase=0;
    while(cin>>N>>Q && N && Q) {
        memset(v, 0, sizeof v);
        memset(s, 0, sizeof s);
        int m=0;
        while(N--) {
            int x;
            cin>>x;
            v[x]++;
            m=max(m, x);
        }
        int rank=v[0];
        for(int i=1;i<=m;i++)
        {
            s[i]=rank;
            rank+=v[i];
        }
        printf("CASE# %d:\n", ++Kase);
        while(Q--) {
            int q;
            cin>>q;
            if(v[q])
                printf("%d found at %d\n", q, s[q]+1);
            else
                printf("%d not found\n", q);
        }
    }
    return 0;
}

2.排序,取lower_bound

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

int main() {
    int N, Q;
    int Kase=0;
    while(cin>>N>>Q && N && Q) {
        vector<int> v;
        while(N--) {
            int x;
            cin>>x;
            v.push_back(x);
        }
        sort(v.begin(), v.end());
        printf("CASE# %d:\n", ++Kase);
        while(Q--) {
            int q;
            cin>>q;
            vector<int>::iterator it=lower_bound(v.begin(), v.end(), q);
            if(it!=v.end() && !(q<*it))
                printf("%d found at %d\n", q, it-v.begin()+1);
            else
                printf("%d not found\n", q);
        }
    }
    return 0;
}
注意找到情况下判断条件

it!=v.end() && !(q<*it))

你可能感兴趣的:(where)