Облачный кризис Все презентации для лекций по АиСД хранятся на диске. Однако из-за…
- User
Облачный кризис
Все презентации для лекций по АиСД хранятся на диске. Однако из-за обилия информации, размеры презентаций всё росли и росли, пока в какой-то момент на диске не закончилась память. Талантливые студенты предложили свою помощь и решили закодировать все презентации с помощью кода Хаффмана.
Входные данные
Дана строка s s из латинских букв нижнего регистра, которая представляет собой некоторый код презентации. ∣ s ∣ ≤ 1 0 6 ∣s∣≤10 6
Выходные данные
Длина строки s s, закодированной кодом Хаффмана. c++
- Assistant
- User
#include #include #include #include
struct Node { char character; int frequency; Node* left = nullptr; Node* right = nullptr; Node(char ch, int freq) { character = ch; frequency = freq; } };
struct Compare { bool operator()(Node* a, Node* b) { return a->frequency > b->frequency; } };
void printCodes(Node* root, std::string str, std::map<char, std::string> &huffmanCode) { if (root == nullptr) return;
if (root->character != '#'){ // '#' is used to represent internal nodes huffmanCode[root->character] = str; } printCodes(root->left, str + "0", huffmanCode); printCodes(root->right, str + "1", huffmanCode);}
int main() { std::string s; std::cin >> s;
std::map<char, int> freq; for (char ch : s) { freq[ch]++; } std::priority_queue<Node*, std::vector<Node*>, Compare> pq; for (auto pair : freq) { pq.push(new Node(pair.first, pair.second)); } while (pq.size() != 1) { Node *left = pq.top(); pq.pop(); Node right = pq.top(); pq.pop(); int sum = left->frequency + right->frequency; pq.push(new Node('#', sum, left, right)); } Node root = pq.top(); std::map<char, std::string> huffmanCode; printCodes(root, "", huffmanCode); int encodedStringLength = 0; for (char ch : s) { encodedStringLength += huffmanCode[ch].length(); } std::cout << encodedStringLength << std::endl; return 0; - Assistant
The error you're encountering states that there is no viable conversion from
Node*(pointer toNode) toNode(object ofNode). This error is happening because you are trying to assign aNode*to a variable of typeNode. Specifically, the error is in the following lines: - User
#include #include #include #include
struct Node { char character; int frequency; Node* left = nullptr; Node* right = nullptr; Node(char ch, int freq) { character = ch; frequency = freq; } Node(char ch, int freq, Node* l, Node* r) { character = ch; frequency = freq; left = l; right = r; } };
struct Compare { bool operator()(Node* a, Node* b) { return a->frequency > b->frequency; } };
void printCodes(Node* root, std::string str, std::map<char, std::string> &huffmanCode) { if (root == nullptr) return;
if (root->character != '#'){ // '#' is used to represent internal nodes huffmanCode[root->character] = str; } printCodes(root->left, str + "0", huffmanCode); printCodes(root->right, str + "1", huffmanCode); - Assistant