huffman编码

来源:互联网 发布:波段王指标源码 编辑:程序博客网 时间:2024/04/27 06:19

 

 在昨晚程序的基础上加进去的. 反转一个string要用到algorithm里面的reverse方法, 原来以为是用string的成员函数

reserve弄来弄去都是错的.自己编了一个程序想反转string也不行,不知道为什么:

void reserve(string a)
{
    
int len = a.length();
    
int i;

    
for(i = 0; i < len/2; i++)
    
{
        a[len
-i-1= a[len-i-1+ a[i];
        a[i] 
= a[len-i-1- a[i];
        a[len
-i-1= a[len-i-1- a[i]; 
    }

}

 

/*
* 文件名:huffman.cpp
* 描述:实现一个huffman树
* 创建日期:2007-11-18
*/

#include
<iostream>
#include
<string>
#include
<algorithm>
using namespace std;

const int MAX = 1000// 最大权值

struct hufnode
{
    
int w; // 权值
    int left; // 左结点
    int right;
    
int par; // 父结点
}
;

struct hufcode
{
    
int w; // 
    string _code; // 
}
;

void huffman(struct hufnode *ar, int n)
{
    
int m1, m2; //存放最小的两个元素 , m1 >= m2
    int x1, x2; // 最小的两个元素的下标
    int i, j, m, k; // 遍历数组的迭代量

    
for(m = n, k = n; k < 2*n-1; m--, k++)
    
{
        m1 
= MAX;
        m2 
= MAX;
        x1 
= 0;
        x2 
= 0;
        i 
= 0;
        j 
= 0;

        
while(i < m)
        
{
            
if(ar[j].par == -1)
            
{
                
if(ar[j].w < m1)
                
{
                    m1 
= ar[j].w;
                    x1 
= j;
                }

                
if(ar[j].w < m2)
                
{
                    m1 
= m2;
                    m2 
= ar[j].w;
                    x1 
= x2;
                    x2 
= j;
                }

                
                i
++;
            }
 // if(ar[i] == -1)

            j
++;
        }
 // while(i)

        
// create huffman tree
        ar[k].left = x1;
        ar[k].right 
= x2;
        ar[k].w 
= ar[x1].w + ar[x2].w;
        ar[x1].par 
= k;
        ar[x2].par 
= k;
    }
 // for(m,k)
}


void hufmancode(struct hufcode *ac, struct hufnode *ar, int n)
{
    
int i, j, k;

    
for(k = 0; k < n; k++)
    
{
        i 
= k;
        ac[k].w 
= ar[i].w;

        
while((j = ar[i].par) != -1)
        
{
            ac[k]._code.push_back((i 
== ar[j].left) ? '0' : '1');
            i 
= j;
        }

        reverse(ac[k]._code.begin(), ac[k]._code.end());
    }

}


int main()
{
    
struct hufnode *ar;
    
struct hufcode *ac;
    
int n;
    
int i;

    cout 
<< "Please input the leaves number N:";
    cin 
>> n;

    ar 
= new struct hufnode[2*n-1];
    ac 
= new struct hufcode[n];

    
// 初始化
    for(i = 0; i < 2*n-1; i++)
    
{
        ar[i].left 
= -1;
        ar[i].right 
= -1;
        ar[i].w 
= 0;
        ar[i].par 
= -1;
    }

    
    
// 输入前n个结点权值
    for(i = 0; i < n; i++)
        cin 
>> ar[i].w;

    huffman(ar, n);

    
for(i = 0; i < 2*n-1; i++)
        cout 
<< ar[i].w << ' ';
    cout 
<< endl;

    hufmancode(ac, ar, n);
    
for(i = 0; i < n; i++)
    
{
        cout 
<< ac[i].w << " ==> " << ac[i]._code << endl;
    }


    
    delete [] ac;
    delete [] ar;

    
return 0;
}

 

 

原创粉丝点击