#include <stdio.h> #include <stdlib.h> struct MinHeapNode { char data; int freq; struct…
- User
#include <stdio.h> #include <stdlib.h>
struct MinHeapNode { char data; int freq; struct MinHeapNode *left, *right; };
struct MinHeap { int size; int capacity; struct MinHeapNode **array; };
struct MinHeapNode* newNode(char data, int freq) { struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp; }
struct MinHeap* createMinHeap(int capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity * sizeof(struct MinHeapNode*)); return minHeap; }
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* t = *a; *a = *b; *b = t; }
void minHeapify(struct MinHeap* minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2;
codeif (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); }}
int isSizeOne(struct MinHeap* minHeap) { return (minHeap->size == 1); }
struct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp; }
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode; }
void buildMinHeap(struct MinHeap* minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i); }
void printCodes(struct MinHeapNode* root, char* str, int top) { if (root->left) { str[top] = '0'; printCodes(root->left, str, top + 1); }
codeif (root->right) { str[top] = '1'; printCodes(root->right, str, top + 1); } if (!root->left && !root->right) { str[top] = '\0'; printf("%c: %s\n", root->data, str); } - Assistant
The above code implements Huffman coding algorithm in C language. It constructs a Huffman tree based on the provided data and frequency arrays, and then prints the generated Huffman codes for each character.
- User
- Assistant
Этот код реализует алгоритм кодирования Хаффмана на языке C.
Структура
MinHeapNodeпредставляет узел в двоичной куче. Узел содержит символ (data), его частоту (freq) и указатели на его левого и правого потомков (leftиright).Структура
MinHeapпредставляет двоичную кучу. Она содержит размер кучи (size), емкость (capacity) и массив указателей на узлы кучи (array).Функция
newNodeсоздает новый узел с заданными символом и частотой.Функция
createMinHeapсоздает новую двоичную кучу с заданной емкостью.Функция
swapMinHeapNodeменяет местами два узла в двоичной куче.Функция
minHeapifyвыполняет операцию корректировки двоичной кучи с заданным индексом, чтобы убедиться, что она удовлетворяет свойству минимальной кучи. - User
напиши программу на си которая будет считывать со строки символы и считать количество каждого символа и записывать и количество и сами символы в массивы
- Assistant
#include <stdio.h> #include <string.h>
#define MAX_SIZE 100
int main() { char str[MAX_SIZE]; int freq[MAX_SIZE] = {0}; char uniqueChars[MAX_SIZE]; int uniqueCount = 0;
codeprintf("Enter a string: "); fgets(str, MAX_SIZE, stdin); int len = strlen(str); for (int i = 0; i < len; i++) { if (str[i] == '\n') { continue; } int found = 0; for (int j = 0; j < uniqueCount; j++) { if (str[i] == uniqueChars[j]) { freq[j]++; found = 1; break; } } if (!found) { uniqueChars[uniqueCount] = str[i]; freq[uniqueCount] = 1; uniqueCount++; } } printf("Character frequencies:\n"); for (int i = 0; i < uniqueCount; i++) { printf("%c: %d\n", uniqueChars[i], freq[i]); } return 0;}