1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <iostream> #include <vector> #include <queue>
using namespace std;
struct HuffmanNode { int weight; HuffmanNode* left; HuffmanNode* right; HuffmanNode(int w) : weight(w), left(nullptr), right(nullptr) {} };
struct Compare { bool operator()(HuffmanNode* a, HuffmanNode* b) { return a->weight > b->weight; } };
int calculateWPL(HuffmanNode* root, int depth) { if (!root) return 0; if (!root->left && !root->right) return root->weight * depth; return calculateWPL(root->left, depth + 1) + calculateWPL(root->right, depth + 1); }
int main() { int n; cin >> n; vector<int> weights(n); for (int i = 0; i < n; ++i) { cin >> weights[i]; } priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq; for (int weight : weights) { pq.push(new HuffmanNode(weight)); } while (pq.size() > 1) { HuffmanNode* left = pq.top(); pq.pop(); HuffmanNode* right = pq.top(); pq.pop(); HuffmanNode* newNode = new HuffmanNode(left->weight + right->weight); newNode->left = left; newNode->right = right; pq.push(newNode); } HuffmanNode* root = pq.top(); int wpl = calculateWPL(root, 0); cout << wpl << endl; return 0; }
|