text: #include <bits/stdc++.h>
  using namespace std;
  typedef pair<int, int> pii;
  
  int heights[1000010];
  
  bool cmp(const pii &p1, const pii &p2) {
    return p1.first > p2.first;
  }
  
  int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
  
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
      cin >> heights[i];
    }
    vector<vector<int>> graph(n, vector<int>{});
    vector<vector<int>> transpose(n, vector<int>{});
    priority_queue<pii, vector<pii>, decltype(&cmp)> pq(&cmp);
    // build right larger
    pq.push({ heights[0], 0 });
    for (int i = 1; i < n; i++) {
      while (!pq.empty()) {
        auto [smallestUnmatched, index] = pq.top();
        if (heights[i] > smallestUnmatched) {
          graph[index].push_back(i);
          transpose[i].push_back(index);
          pq.pop();
        } else {
          break;
        }
      }
      pq.push({ heights[i], i });
    }
    // build left larger
    pq = priority_queue<pii, vector<pii>, decltype(&cmp)> (&cmp);
    pq.push({ heights[n - 1], n - 1 });
    for (int i = n - 2; i >= 0; i--) {
      while (!pq.empty()) {
        auto [smallestUnmatched, index] = pq.top();
        if (heights[i] > smallestUnmatched) {
          graph[index].push_back(i);
          transpose[i].push_back(index);
          pq.pop();
        } else {
          break;
        }
      }
      pq.push({ heights[i], i });
    }
  
    // do bfs
    vector<int> dist(n, -1);
    queue<pii> bfs;
    for (int i = 0; i < n; i++) {
      if (graph[i].size() == 0) {
        bfs.push({ i, 0 });
      }
    }
    while (!bfs.empty()) {
      pii top = bfs.front(); bfs.pop();
      dist[top.first] = top.second;
      for (auto neighbour : transpose[top.first]) {
        if (dist[neighbour] == -1) {
          dist[neighbour] = top.second + 1;
          bfs.push({ neighbour, top.second + 1 });
        }
      }
    }
    for (int i = 0; i < n; i++) {
      cout << dist[i] << " ";
    }
    cout << endl;
  }
  