CSES - Shared codeLink to this code:
https://cses.fi/paste/ecb0b446265e23514035ea/
#include <bits/stdc++.h>
using pii=std::pair<int,int>;
using namespace std;
const int maxn = 2e5 + 5, maxbit = 17;
int n, x[maxn], p, bit[maxn];
void add(int idx, int val)
{
for(++idx; idx < maxn; idx += idx & -idx)
bit[idx] += val;
}
int get(int idx)
{
int cursum = 0;
for(++idx; idx > 0; idx -= idx & -idx)
cursum += bit[idx];
return cursum;
}
int get_fi_pos(int val)
{
int lo = 0, hi = n - 1, mid;
while(lo < hi)
{
mid = (lo + hi) / 2;
if(get(mid) >= val)
hi = mid;
else
lo = mid + 1;
}
assert(lo == hi);
return lo;
}
int32_t main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> x[i];
add(i, 1);
}
for(int i = 0; i < n; i++)
{
cin >> p;
int pos = get_fi_pos(p);
cout << x[pos] << " ";
add(pos, -1);
}
cout << "\n";
return 0;
}