题目链接
ZJU 数据结构课程04-6构造完全二叉树
https://pintia.cn/problem-sets/951072707007700992/problems/977489256881188864
分析
很简单,自顶向下,递归构造就好 O(nlogn);
code
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
const int maxn = 1e3 +10;
int n;
int a[maxn];
std::vector<int> ans;
std::vector<int> tree[maxn];
void solve(int l,int r,int fa) {
// std::cout << l << " " << r << '\n';
if(l==r){
tree[fa].pb(l);
return;
}
if(l>r)return;
int num = r -l +1;
int h = ceil(log2(num+1));
int left = (1<<h) -1 -num;
int sz = (num-left-1)/2;
int last = 1<<(h-2);
int sz_l = left+ sz;
if(last < left)sz_l = last+sz;
tree[fa].pb(l+sz_l);
solve(l,l+sz_l-1,l+sz_l);
solve(l+sz_l+1,r,l+sz_l);
}
void bfs(int root) {
queue<int> Q;
Q.push(root);
while (!Q.empty()) {
int v = Q.front();Q.pop();
// std::cout << a[v] << '\n';
ans.pb(a[v]);
if(tree[v].size()>0){
for(int e : tree[v]){
Q.push(e);
}
}
}
}
int main(int argc, char const *argv[]) {
/* code */
cin>>n;
for(int i=1 ; i<=n ; ++i)scanf("%d",a+i );
sort(a+1,a+n+1);
solve(1,n,0);
bfs(tree[0][0]);
for(int i=0 ; i<ans.size()-1 ; ++i)printf("%d ", ans[i]);
printf("%d", ans[n-1]);
return 0;
}