杂项 哈夫曼树

来源:互联网 发布:大数据处理算法 编辑:程序博客网 时间:2024/05/29 02:27

qsort

Defined in header
void qsort( void ptr, std::size_t count, std::size_t size, /*compare-pred/* comp );
void qsort( void ptr, std::size_t count, std::size_t size, /*c-compare-pred/* comp );

Sorts the given array pointed to by ptr in ascending order. The array contains count elements of size bytes. Function pointed to by comp is used for object comparison.
If comp indicates two elements as equivalent, their order is undefined.

Parametersptr -   pointer to the array to sortcount   -   number of elements in the arraysize    -   size of each element in the array in bytescomp    -   comparison function which returns ​a negative integer value if the first argument is less than the second

cin.getline()

注意会把第一个几个数字的那个空格也读进来, 所以要读n+1次
cin.getline 编辑
此函数会一次读取多个字符(包括空白字符)。它以指定的地址为存放第一个读取的字符的位置,依次向后存放读取的字符,直到读满N-1个,或者遇到指定的结束符为止。若不指定结束符,则默认结束符为’\n’。其语法为:
cin.getline(字符指针(char*),字符个数N(int),结束符(char));
例:12345678910

#include <iostream>using namespace std;int main(){    char a[30];    cin.getline(a, 10);    for( int i=0; i<10; i++ )        cout << a[i] << " ";    return 0;}

输入:1234567890123
输出:1 2 3 4 5 6 7 8 9 _ (第10位存放字符串结束符’\0’)

Huffman树

#include <iostream>#include <queue>using namespace std;struct MinHeapNode {    char data;    int freq;    MinHeapNode* left, *right;    MinHeapNode(char data, int freq) {        this->data = data;        this->freq = freq;        this->left = this->right = NULL;    }};struct compare {    bool operator() (MinHeapNode* l, MinHeapNode* r) {        return l->freq > r->freq;    }};//int my_counter = 0;void printCodes(struct MinHeapNode* root, string str) {    if (!root) {        return;    }    if (root->data != '$') {        cout << root->data << " : " << str << '\n';        //my_counter += str.size();    }    printCodes(root->left, str + '0');    printCodes(root->right, str + '1');}void HuffmanCodes(char data[], int freq[], int size) {    struct MinHeapNode* left, *right, *top;    priority_queue<MinHeapNode* , vector<MinHeapNode*>, compare> minHeap;    for (int i = 0; i < size; i++) {        minHeap.push(new MinHeapNode(data[i], freq[i]));    }    while (minHeap.size() != 1) {        left = minHeap.top();        minHeap.pop();        right = minHeap.top();        minHeap.pop();        top = new MinHeapNode('$', left->freq + right->freq);        top->left = left;        top->right = right;        minHeap.push(top);    }    printCodes(minHeap.top(), "");}int main() {    char arr[] = {'a', 'b', 'c', 'd'};    int freq[] = {11, 11, 11, 11};    int size = sizeof(arr) / sizeof(arr[0]);    HuffmanCodes(arr, freq, size);    return 0;}
原创粉丝点击