# Include <iostream> # include <stdlib. h ># define n 30000 using namespace STD; int A [n + 1], O = 0; typedef struct {int weight; int parent, lchild, rchild;} htnode; typedef struct {int weight;} htcode; void huffmanselect (htnode HT [], int K, int * S1, int * S2) // select the two smallest nodes to be given. {int I; for (I = 1; I <= K & HT [I]. parent! = 0; I ++) {;}* S1 = I; for (I = 1; I <= K; I ++) {If (HT [I]. parent = 0 & HT [I]. weight <HT [* S1]. weight) * S1 = I;} for (I = 1; I <= K; I ++) {If (HT [I]. parent = 0 & I! = * S1) break;} * S2 = I; for (I = 1; I <= K; I ++) {If (HT [I]. parent = 0 & HT [I]. weight <HT [* s2]. weight & I! = * S1) * S2 = I;} void huffmantree (htnode HT [], htcode HC [], int N) // construct the Harman tree {int I, m, S1, s2; M = 2 * n-1; for (I = 1; I <= m; I ++) {if (I <= N) HT [I]. weight = HC [I]. weight; elseht [I]. parent = 0; HT [I]. parent = HT [I]. lchild = HT [I]. rchild = 0;} for (I = n + 1; I <= m; I ++) {huffmanselect (HT, I-1, & S1, & S2 ); HT [S1]. parent = I; HT [s2]. parent = I; HT [I]. lchild = S1; HT [I]. rchild = S2; HT [I]. weight = HT [S1]. weight + HT [s2]. weight; A [O ++] = HT [I]. weight; // exist in the array for each constructed root} int Main () {int N, I, j, S = 0; htnode HT [n + 1]; htcode HC [n + 1]; CIN> N; for (I = 1; I <= N; I ++) {CIN> HC [I]. weight;} huffmantree (HT, HC, n); For (j = 0; j <O; j ++) {S + = A [J];} cout <S <Endl; return 0;} // Method 1: User tree // Method 2: Use of priority queue # include <stdio. h ># include <queue >#include <algorithm> using namespace STD; int main () {int num; int N, I, A; priority_queue <int> plank; // <use of priority queue> long int sum; while (scanf ("% d", & N) in the ascending order of priority queue )! = EOF) {sum = 0; while (n --) {scanf ("% d", & num); plank. push (-num);} while (plank. size ()! = 1) {A = plank. top (); plank. pop (); A + = plank. top (); sum + = A; plank. pop (); plank. push (a);} plank. pop (); printf ("% LLD \ n",-sum);} return 0 ;}
Sdutoj 2127 tree-Heap Structure exercise-combine the fruit of the Harman tree