結果

問題 No.3134 二分探索木
ユーザー tobbie
提出日時 2025-05-29 21:41:11
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
RE  
実行時間 -
コード長 1,449 bytes
コンパイル時間 2,739 ms
コンパイル使用メモリ 196,500 KB
実行使用メモリ 7,848 KB
最終ジャッジ日時 2025-05-29 21:41:18
合計ジャッジ時間 6,469 ms
ジャッジサーバーID
(参考情報)
judge2 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample RE * 5
other RE * 15
権限があれば一括ダウンロードができます
コンパイルメッセージ
main.cpp: In function ‘int main()’:
main.cpp:44:18: warning: ‘tree’ may be used uninitialized [-Wmaybe-uninitialized]
   44 |     tree = insert(tree, a[i], 0);
      |            ~~~~~~^~~~~~~~~~~~~~~
main.cpp:42:16: note: ‘tree’ was declared here
   42 |   struct Node *tree;
      |                ^~~~

ソースコード

diff #

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

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

struct Node {
  int value;
  int depth;
  int child;
  Node *left;
  Node *right;
};

struct Node* insert(struct Node *node, int x, int dp) {
  if (node == NULL) {
    struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->value = x;
    newNode->depth = dp;
    newNode->child = 0;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
  }
  if (x < node->value)
    node->left = insert(node->left, x, dp + 1);
  else
    node->right = insert(node->right, x, dp + 1);
  int cl = node->left == NULL ? 0 : node->left->child + 1;
  int cr = node->right == NULL ? 0 : node->right->child + 1;
  node->child = cl + cr;
  return node;
}

int main() {
  int n;
  cin >> n;
  vector<int> a(n), ainv(n+1);
  rep(i, n) {
    cin >> a[i];
    ainv[a[i]] = i;
  }
  struct Node *tree;
  rep(i, n) {
    tree = insert(tree, a[i], 0);
  }
  vector<int> b(n), c(n);
  auto dfs = [&](auto dfs, struct Node *node) -> void {
    if (node == NULL)
      return;
    b[ainv[node->value]] = node->depth;
    c[ainv[node->value]] = node->child;
    dfs(dfs, node->left);
    dfs(dfs, node->right);
  };
  dfs(dfs, tree);
  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