Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Đếm phần tử nhỏ hơn bên phải dùng Set C++ STL

Cho mảng, xây dựng mảng mới với số phần tử nhỏ hơn ở bên phải của mỗi vị trí.

Ví dụ

#include <bits/stdc++.h>
using namespace std;

void count_Rsmall(int A[], int len) {
    set<int> s;
    int countSmaller[len];
    for (int i = len - 1; i >= 0; i--) {
        s.insert(A[i]);
        auto it = s.lower_bound(A[i]);
        countSmaller[i] = distance(s.begin(), it);
    }
    for (int i = 0; i < len; i++) cout << countSmaller[i] << " ";
}

int main() {
    int A[] = {12, 1, 2, 3, 0, 11, 4};
    int len = sizeof(A) / sizeof(int);
    count_Rsmall(A, len);
    return 0;
}

Đầu ra

6 1 1 1 0 1 0