DEV Community

Guhan M
Guhan M

Posted on Edited on

List Removals | CSES - Algoritmit ongelmanratkaisussa

Problem: https://cses.fi/alon/task/1749

#include <iostream>
#include <vector>

using namespace std;

int n;
long long arr[200001];
vector<int> tree;
int treeLen;
int p;

void change(int k, int x) {
    k += treeLen;
    tree[k] = x;
    for (k /= 2; k >= 1; k /= 2) {
        tree[k] = tree[k * 2] + tree[k * 2 + 1];
    }
}

int getKth(int k) {
    int currIdx = 1;
    while (currIdx < treeLen) {
        int leftCount = tree[2 * currIdx];
        if (k < leftCount) {
            currIdx *= 2;
        } else {
            currIdx = currIdx * 2 + 1;
            k -= leftCount;
        }
    }
    change(currIdx - treeLen, 0);
    return currIdx - treeLen;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n;

    treeLen = 1;
    while (treeLen < n) treeLen *= 2;
    tree.resize(2 * treeLen, 0);

    for (int i = 0; i < n; i++) {
        change(i, 1);
        cin >> arr[i];
    }

    for (int i = 0; i < n; i++) {
        cin >> p;
        cout << arr[getKth(p - 1)] << ' ';
    }
    cout << '\n';

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)