P1918 保龄球 题解


题目传送门

一、二分搜索法

#include 

using namespace std;

typedef long long LL;
typedef pair PII;
const int N = 1e5 + 10;
int n, q;
PII a[N];

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i].first;
        a[i].second = i;
    }
    sort(a + 1, a + 1 + n); //PII默认排序是按first排的
    cin >> q;
    while (q--) {
        int m;
        cin >> m;
        int l = 1, r = n;
        while (l < r) {
            int mid = l + r >> 1;
            if (a[mid].first >= m) r = mid;    // check()判断mid是否满足性质
            else l = mid + 1;
        }
        if (a[l].first == m) cout << a[l].second << endl;
        else cout << 0 << endl;
    }
    return 0;
}

二、STL法

#include 

using namespace std;
int n, q;
unordered_map _map;

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        int cnt;
        cin >> cnt;
        _map[cnt] = i;
    }
    cin >> q;
    while (q--) {
        int m;
        cin >> m;
        cout << _map[m] << endl;
    }
    return 0;
}