結果
| 問題 |
No.3134 二分探索木
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2025-05-23 14:32:07 |
| 言語 | C++23 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 170 ms / 2,000 ms |
| コード長 | 2,617 bytes |
| コンパイル時間 | 3,899 ms |
| コンパイル使用メモリ | 282,912 KB |
| 実行使用メモリ | 18,944 KB |
| 最終ジャッジ日時 | 2025-05-23 14:32:15 |
| 合計ジャッジ時間 | 6,940 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 5 |
| other | AC * 15 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N;
vector<int> A(N), idx(N+1);
for(int i = 0; i < N; i++){
cin >> A[i];
idx[A[i]] = i; // value → 挿入順 index のマッピング
}
vector<int> parent(N, -1), depth(N, 0);
vector<int> leftChild(N, -1), rightChild(N, -1);
set<int> S; // 挿入済みの値を保持し、前後関係を探す
// 1つめの要素を根に
S.insert(A[0]);
depth[0] = 0; // 根の深さは 0
// 2つ目以降を順に BST に挿入
for(int i = 1; i < N; i++){
int x = A[i];
auto it = S.lower_bound(x);
bool hasSucc = (it != S.end());
bool hasPred = (it != S.begin());
int p = -1;
if(hasPred){
int predVal = *prev(it);
int predIdx = idx[predVal];
// 「前駆要素の右子が空いていれば」そこに attach
if(rightChild[predIdx] == -1){
p = predIdx;
rightChild[p] = i;
}
}
if(p == -1){
// そうでなければ後駆要素の左子に attach
int succVal = *it; // it != end() は保証されている
int succIdx = idx[succVal];
p = succIdx;
leftChild[p] = i;
}
parent[i] = p;
depth[i] = depth[p] + 1;
S.insert(x);
}
// --- 子孫数を求めるための後順走査 ---
// 非再帰でポストオーダーを得るトリック
vector<int> stack, post;
stack.reserve(N);
post.reserve(N);
stack.push_back(0); // 根は挿入 0 番目
while(!stack.empty()){
int u = stack.back(); stack.pop_back();
post.push_back(u);
if(leftChild[u] != -1) stack.push_back(leftChild[u]);
if(rightChild[u] != -1) stack.push_back(rightChild[u]);
}
// post に対して逆順にすると「子→親」の順になる
vector<int> subtree_size(N, 0);
for(int k = N-1; k >= 0; k--){
int u = post[k];
subtree_size[u] = 1;
if(leftChild[u] != -1) subtree_size[u] += subtree_size[leftChild[u]];
if(rightChild[u] != -1) subtree_size[u] += subtree_size[rightChild[u]];
}
// 出力
// 1行目: 深さ B_i
for(int i = 0; i < N; i++){
cout << depth[i] << (i+1<N ? ' ' : '\n');
}
// 2行目: 子孫数 C_i = subtree_size - 1
for(int i = 0; i < N; i++){
cout << (subtree_size[i] - 1) << (i+1<N ? ' ' : '\n');
}
return 0;
}