#51427: cpp有內建函式


kenny980721.tu@gmail.com (有事直接私)

學校 : 國立中興大學附屬高級中學
編號 : 290039
來源 : [220.134.29.87]
最後登入時間 :
2025-09-13 17:26:11

lower_bound(first,last,val)

回傳第一個>=val的位置,如果找不到,回傳last

在algorithm裡

 

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

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n;
    cin >> n;
    
    int m;
    cin >> m;
    
    vector<int> A(n);
    for (int i = 0; i < n; i++) cin >> A[i];
    
    long long total = 0;
    while (m--) {
        int a;
        cin >> a;
        auto it = lower_bound(A.begin(), A.end(), a);
        if (it == A.end()) {
            total += (n + 1) * 2;
        }
        else {
            total += ((it - A.begin()) + 1) * 2;
        }
    }
    cout << total;
}

 

有錯歡迎指教