maruma

Untitled

Nov 4th, 2023 (edited)
565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | Source Code | 0 0
  1. //wit: cout
  2. //rit: cin
  3. struct bst{
  4.     struct Node{ //node
  5.         Node *l, *r;
  6.         ll f;
  7.         int pos, num;
  8.         Node(ll fq, int x){
  9.             f = fq;
  10.             l = r = nullptr;
  11.             pos = x;
  12.             num = 1;
  13.         }
  14.     };
  15.     using node = Node*;
  16.     struct comp{ //comp for priority_queue
  17.         bool operator()(node a, node b){
  18.             return (
  19.                 a -> f > b ->f ||
  20.                 (a -> f == b -> f && a -> num < b -> num)
  21.             );
  22.         }
  23.     };
  24.     node root;
  25.     int size;
  26.     bst(vector<ll> &vec){
  27.         size = vec.size();
  28.         priority_queue<node, vector<node>, comp> pq;
  29.         for(int i = 0; i < size; i++){ //push elements into pq
  30.             node a = new Node(vec[i], i);
  31.             pq.push(a);
  32.         }
  33.         while(pq.size() != 1){ //combine every two smallest
  34.             node left = pq.top();
  35.             pq.pop();
  36.             node right = pq.top();
  37.             pq.pop();
  38.             node rt = new Node(left -> f + right -> f, -1);
  39.             rt -> l = left;
  40.             rt -> r = right;
  41.             rt -> num += left -> num + right -> num;
  42.             pq.push(rt);
  43.         }
  44.         root = pq.top();
  45.     }
  46.     void _print(vector<string> &v, node root, string str){ //put str into vector
  47.         if(root -> l)
  48.             _print(v, root -> l, str + "0");
  49.         if(root -> r)
  50.             _print(v, root -> r, str + "1");
  51.         if(!root -> l && !root->r){
  52.             v[root -> pos] = str;
  53.             return;
  54.         }
  55.     }
  56.     void print(){ //print vector
  57.         vector<string> strs(size, "");
  58.         _print(strs, root, "");
  59.         for(int i = 0; i < size; i++){
  60.             wit(strs[i]), wit('\n');
  61.         }
  62.     }
  63. };
  64. int main(){
  65.     cin.tie(nullptr);
  66.     cout.tie(nullptr);
  67.     ios::sync_with_stdio(false);
  68.     int f, n; rit(n);
  69.     vector<ll> fs(n, 0);
  70.     for(int i = 0; i < n; i++)
  71.         rit(fs[i]);
  72.     bst tree(fs);
  73.     tree.print();
  74. }
Advertisement
Add Comment
Please, Sign In to add comment