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 : Permutation Transformation

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

vector<int> depth;

void populate_depths(vector<int> &p, int l, int r, int current_depth) {
    if (l > r) {
        return;
    }

    // Locate the maximum element.
    int idx = max_element(p.begin() + l, p.begin() + r + 1) - p.begin();
    depth[p[idx]] = current_depth;
    populate_depths(p, l, idx - 1, current_depth + 1);
    populate_depths(p, idx + 1, r, current_depth + 1);
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        vector<int> p(n);
        for (int i = 0; i < n; i++) {
            cin >> p[i];
            p[i]--;
        }
        depth.clear();
        depth.resize(n);
        populate_depths(p, 0, n - 1, 0);
        for (int i = 0; i < n; i++) {
            cout << depth[p[i]] << " ";
        }
        cout << endl;
    }
}