Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //wit: cout
- //rit: cin
- struct bst{
- struct Node{ //node
- Node *l, *r;
- ll f;
- int pos, num;
- Node(ll fq, int x){
- f = fq;
- l = r = nullptr;
- pos = x;
- num = 1;
- }
- };
- using node = Node*;
- struct comp{ //comp for priority_queue
- bool operator()(node a, node b){
- return (
- a -> f > b ->f ||
- (a -> f == b -> f && a -> num < b -> num)
- );
- }
- };
- node root;
- int size;
- bst(vector<ll> &vec){
- size = vec.size();
- priority_queue<node, vector<node>, comp> pq;
- for(int i = 0; i < size; i++){ //push elements into pq
- node a = new Node(vec[i], i);
- pq.push(a);
- }
- while(pq.size() != 1){ //combine every two smallest
- node left = pq.top();
- pq.pop();
- node right = pq.top();
- pq.pop();
- node rt = new Node(left -> f + right -> f, -1);
- rt -> l = left;
- rt -> r = right;
- rt -> num += left -> num + right -> num;
- pq.push(rt);
- }
- root = pq.top();
- }
- void _print(vector<string> &v, node root, string str){ //put str into vector
- if(root -> l)
- _print(v, root -> l, str + "0");
- if(root -> r)
- _print(v, root -> r, str + "1");
- if(!root -> l && !root->r){
- v[root -> pos] = str;
- return;
- }
- }
- void print(){ //print vector
- vector<string> strs(size, "");
- _print(strs, root, "");
- for(int i = 0; i < size; i++){
- wit(strs[i]), wit('\n');
- }
- }
- };
- int main(){
- cin.tie(nullptr);
- cout.tie(nullptr);
- ios::sync_with_stdio(false);
- int f, n; rit(n);
- vector<ll> fs(n, 0);
- for(int i = 0; i < n; i++)
- rit(fs[i]);
- bst tree(fs);
- tree.print();
- }
Advertisement
Add Comment
Please, Sign In to add comment