結果

問題 No.3134 二分探索木
ユーザー tobbie
提出日時 2025-05-30 22:06:51
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,542 bytes
コンパイル時間 2,274 ms
コンパイル使用メモリ 199,784 KB
実行使用メモリ 31,488 KB
最終ジャッジ日時 2025-05-30 22:06:59
合計ジャッジ時間 7,767 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3 WA * 2
other AC * 2 WA * 8 TLE * 1 -- * 4
権限があれば一括ダウンロードができます

ソースコード

diff #

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

#define rep(i, n) for (int i = 0; i < (int)n; i++)

struct Node {
  int p;
  int l;
  int r;
  Node (int p, int l, int r) : p(p), l(l), r(r) {}
};

void insert(vector<struct Node> &node, int a, int b, int x) {
  if (x == a) {
    node[x].p = 0;
    return;
  }
  if (x < b && b < a) {
    node[b].l = x;
    node[x].p = b;
    return;
  }
  if (x > b && b > a) {
    node[b].r = x;
    node[x].p = b;
    return;
  }
  while (1) {
    if (x < a) {
      if (node[a].l == -1) {
	node[a].l = x;
	node[x].p = a;
	break;
      }
      node[x].p = a;
      a = node[a].l;
      continue;
    }
    if (x > a) {
      if (node[a].r == -1) {
	node[a].r = x;
	node[x].p = a;
	break;
      }
      node[x].p = a;
      a = node[a].r;
    }
  }
}

int main() {
  int n;
  cin >> n;
  vector<struct Node> node(n, {-1, -1, -1});
  vector<int> a(n), ainv(n);
  rep(i, n) {
    cin >> a[i]; a[i]--;
    if (i == 0)
      insert(node, a[0], a[0], a[i]);
    else
      insert(node, a[0], a[i-1], a[i]);
    ainv[a[i]] = i;
  }
  vector<int> b(n), c(n);
  auto dfs = [&](auto dfs, int a, int d) {
    if (a == -1)
      return 0;
    int r = 0;
    b[ainv[a]] = d;
    r += dfs(dfs, node[a].l, d + 1);
    r += dfs(dfs, node[a].r, d + 1);
    c[ainv[a]] = r;
    return r + 1;
  };
  dfs(dfs, a[0], 0);
  rep(i, n) {
    cout << b[i];
    if (i < n-1) cout << " ";
    else         cout << endl;
  }
  rep(i, n) {
    cout << c[i];
    if (i < n-1) cout << " ";
    else         cout << endl;
  }
  return 0;
}
0