CSES - Shared codeLink to this code:
https://cses.fi/paste/631ad9c4df8953464035cd/
// This is NOT my code.
// See https://codeforces.com/blog/entry/104650#comment-929666
#include<bits/stdc++.h>
#define X first
#define Y second
#define all(x) begin(x), end(x)
#define FOR(i, a, b) for(int i = (a); i <= (b); i++)
#define FORD(i, b, a) for(int i = (b); i >= (a); i--)
#define REP(i, a, b) for (int i = (a); i < (b); i++)
#define mxx max_element
#define mnn min_element
#define SQR(x) (1LL * (x) * (x))
#define MASK(i) (1LL << (i))
using namespace std;
typedef long long ll;
typedef double db;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef pair<ll, pll> plll;
typedef pair<ll, int> pli;
template<class A, class B>
void maximize(A& x, B y) {
if (x < y) x = y;
}
template<class A, class B>
void minimize(A& x, B y) {
if (x > y) x = y;
}
/* END OF TEMPLATE */
int n, x;
struct Node {
Node* child[10];
int cnt, val;
Node() {
REP(i, 0, 10) child[i] = NULL;
cnt = val = 0;
}
};
Node* root = new Node();
void add(string& s, int val) {
Node* p = root;
for (auto x : s) {
if (p->child[x - 48] == NULL) p->child[x-48] = new Node();
p = p->child[x - 48];
p->cnt++; // string passed
}
p->val = val;
}
// find and remove
int dfs(Node* p, int k) {
while (k > 0) {
bool kt = true;
REP(i, 0, 10)
if (p->child[i] != NULL) {
// if p->child[i]->cnt == 0, it deleted.
if (p->child[i]->cnt !=0 && p->child[i]->cnt >= k) {
p->child[i]->cnt--;
p = p->child[i];
kt = false;
break;
}
else k-=p->child[i]->cnt;
}
if (kt) break;
}
return p->val;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin>>n;
FOR(i, 1, n) {
cin>>x;
string s = to_string(i);
while ((int)s.size() < 8) s = "0" + s; // make all string of index have the same length
add(s, x);
}
FOR(i, 1, n) {
cin>>x;
cout<<dfs(root, x)<<" ";
}
return 0;
}