构造霍夫曼树

来源:互联网 发布:java 字符串截取 编辑:程序博客网 时间:2024/05/29 03:30
#include<iostream>#include<vector>#include<string>#include<algorithm>using namespace std;struct node{    int val;    struct node *left;    struct node *right;    node(int i) : val(i), left(NULL), right(NULL){    }};int fun(node *root, int time){    if (root->left == NULL && root->right == NULL){        return time * root->val;    }    return fun(root->left, time + 1) + fun(root->right, time + 1);}int main(){    string str;    while (cin >> str){        vector<int> table(256);        for (int i = 0; i < str.size(); ++i)            table[str[i]]++;        vector<int> value;        for (int i = 0; i < 256; ++i){            if (table[i])                value.push_back(table[i]);        }        sort(value.begin(), value.end());        vector<int> temp;        vector<node *> tempNode;        temp.push_back(value[0] + value[1]);        node *a = new node(value[0]);        node *b = new node(value[1]);        node *c = new node(value[0] + value[1]);        c->left = a; c->right = b;        tempNode.push_back(c);        int i = 2, j = 0;        for (int k = 2; k < value.size(); ++k){            int oldI = i;            int time = 0;            while (time < 2){                if (i < value.size()){                    if (j < temp.size()){                        if (value[i] < temp[j])                            i++;                        else                            j++;                    }                    else                        i++;                }                else                    j++;                ++time;            }            if (i - oldI == 0){                a = tempNode[j - 1];                b = tempNode[j - 2];            }            else if (i - oldI == 1){                a = tempNode[j - 1];                b = new node(value[i - 1]);            }            else{                a = new node(value[i - 1]);                b = new node(value[i - 2]);            }            c = new node(a->val + b->val);            c->left = a; c->right = b;            tempNode.push_back(c);            temp.push_back(c->val);        }        node *head = tempNode.back();        cout << fun(head, 0) << endl;    }    return 0;}
 求带权路径:#include <cstdio>#include <cstring>#include <cstdlib>#include <cmath>#include <algorithm>#include <utility>#include <queue>using namespace std;int main(){    char s[3300];    while(scanf("%s",s) != EOF){        int n = strlen(s);        sort(s,s + n);        priority_queue<int> heap;        int cnt = 0;        for(int i = 0,j;i < n;){            j = i;            while(j < n && s[j] == s[i]) ++ j;            heap.push(i - j);            i = j;            ++ cnt;        }        int ret = 0;        for(int i = 0;i < cnt - 1;++ i){            int A = heap.top(); heap.pop();            int B = heap.top(); heap.pop();            ret -= A + B;            heap.push(A + B);        }          printf("%d\n",ret);    }    return 0;}
0 0
原创粉丝点击