結果

問題 No.3134 二分探索木
ユーザー tobbie
提出日時 2025-05-31 13:54:17
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
実行時間 -
コード長 1,808 bytes
コンパイル時間 2,144 ms
コンパイル使用メモリ 197,400 KB
実行使用メモリ 13,312 KB
最終ジャッジ日時 2025-05-31 13:54:24
合計ジャッジ時間 7,133 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 8 TLE * 1 -- * 6
権限があれば一括ダウンロードができます

ソースコード

diff #

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

#define rep(i, n) for (int i = 0; i < (int)n; i++)
#define rep1(i, j, n) for (int i = (int)j; 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 r, int x) {
  if (x == r) {
    node[x].p = 0;
    return;
  }
  while (1) {
    if (x < r) {
      if (node[r].l == -1) {
	node[r].l = x;
	node[x].p = r;
	break;
      }
      node[x].p = r;
      r = node[r].l;
      continue;
    }
    if (x > r) {
      if (node[r].r == -1) {
	node[r].r = x;
	node[x].p = r;
	break;
      }
      node[x].p = r;
      r = node[r].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]--;
    ainv[a[i]] = i;
  }
  rep(i, n) {
    int x0 = a[0];
    int x = a[i];
    if (x < x0) {                       // left of previous
      if (x < a[0] && x0 < a[0]) {      // left of root
	while (x < node[x0].p) {
	  x0 = node[x0].p;
	}
	insert(node, x0, x);
      } else {
	insert(node, a[0], x);
      }
    }
    if (x > x0) {
      if (x > a[0] && x0 > a[0]) {
	while (x > node[x0].p) {
	  x0 = node[x0].p;
	}
	insert(node, x0, x);
      } else {
	insert(node, a[0], x);
      }
    }
  }
  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