Sicily 3703. Huffman Coding V1

来源:互联网 发布:matlab矩阵符号运算 编辑:程序博客网 时间:2024/05/29 08:19

Huffman树……自己查了下资料才知道具体是怎么弄出来的,基本步骤是:
1.在节点集合中找出权值最小的两个节点,小者居左大者居右,并从集合中删除;
2.将上面找到的两个节点合二为一(权值),添加到节点集合;
3.重复上述步骤直到只剩下一个节点,此节点即为根节点;
4.查找某一个节点的编码时,从根节点出发,往左是0,往右是1,直到找到这个节点(必为叶子),整个历程就是这个节点的编码。
其实Huffman树并不是唯一的,因为若两个节点的权值相等时,左右子树并不确定。这道题中没有说明这种情况如何处理,因为数据并不会出现这样的情况(已测试),大家爱怎么处理就怎么处理。

Run Time: 0sec

Run Memory: 312KB

Code length: 1627Bytes

Submit Time: 2012-01-05 01:13:13

// Problem#: 3703// Submission#: 1174156// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/// All Copyright reserved by Informatic Lab of Sun Yat-sen University#include <iostream>#include <vector>#include <string>using namespace std;struct Node {    string s;    int weight;    Node( string code, int n ) { s = code; weight = n; }};vector<Node> v;vector<Node>::iterator it;void encode( string s, int n ) {    for ( it = v.begin(); it != v.end(); it++ ) {        if ( n >= it->weight )            break;    }    v.insert( it, Node( s, n ) );}int main(){    int n;    int i;    int keep;    char c;    string s, left, right;    int freq[ 26 ] = { };    string code[ 26 ] = { };    cin >> n;    while ( n-- ) {        cin >> c;        freq[ c - 'A' ]++;    }    for ( i = 0; i < 26; i++ ) {        if ( freq[ i ] != 0 ) {            s = 'A' + i;            encode( s, freq[ i ] );        }    }    while ( v.size() != 1 ) {        left = v.back().s;        for ( i = 0; i < left.size(); i++ )            code[ left[ i ] - 'A' ] = '0' + code[ left[ i ] - 'A' ];        keep = v.back().weight;        v.pop_back();        right = v.back().s;        for ( i = 0; i < right.size(); i++ )            code[ right[ i ] - 'A' ] = '1' + code[ right[ i ] - 'A' ];        keep += v.back().weight;        v.pop_back();        encode( left + right, keep );    }    while ( true ) {        keep = 0;        for ( i = 1; i < 26; i++ ) {            if ( freq[ i ] > freq[ keep ] )                keep = i;        }        if ( freq[ keep ] != 0 ) {            cout << (char)('A' + keep) << " " << freq[ keep ] << " " << code[ keep ] << endl;            freq[ keep ] = 0;        }        else            break;    }    return 0;}                                 


原创粉丝点击