Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

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

vector<int> solve(vector<int> &p, int k) {
    int n = p.size();
    for (int i = 0; i < n; i++) {
        p[i]--;
    }

    int available_group_id = 0;
    map<int, vector<int>> group_elements;
    vector<int> group_id(n), eaten_at_round(n, -1);
    set<int> table;
    for (int i = 0; i < n; i++) {
        int x = p[i];
        auto itr = table.lower_bound(x);
        if (itr != table.end()) {
            int parent = *itr;
            table.erase(parent);
            table.insert(x);

            group_id[x] = group_id[parent];
            group_elements[group_id[x]].push_back(x);
        } else {
            // Create a new group
            group_id[x] = available_group_id;
            group_elements[group_id[x]].push_back(x);
            table.insert(x);
            available_group_id++;
        }

        // Handling the deletion only inside the "if" block is incorrect, as
        // k can also be equal to 1.
        vector<int> &group_now = group_elements[group_id[x]];
        if ((int)group_now.size() == k) {
            for (int &ele : group_now) {
                eaten_at_round[ele] = i + 1;
            }
            // Make sure to do cleanup from table as well.
            table.erase(x);
        }
    }

    return eaten_at_round;
}

int main() {
    int n, k;
    cin >> n >> k;

    vector<int> p(n);
    for (int i = 0; i < n; i++) {
        cin >> p[i];
    }

    vector<int> res = solve(p, k);
    for (int i = 0; i < n; i++) {
        cout << res[i] << "\n";
    }
}