Visitors hit counter dreamweaver

多媒体技术 有损压缩算法之LZW编码算法

    Lempel_Ziv_Welch(LZW)算法利用了一种自适应的,基于字典的压缩技术。LZW编码器在接收数据时动态地创建字典。LZW在实现过程中不断将越来越长的重复条目插入字典中,然后将字符串的编码而不是字符串本身发送出去。  根据书上的伪代码(Pseudo code),也能很快的把程序写出。到此,多媒体第一次作业的四个算法都完成了。又可以有时间去刷题和搞搞java了。hiahiahia。。。。加油哦~孩子

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct dict{
    int  code;
    string str;
    dict(){}
};
dict dicts[100];

int main()
{
    //Initialize the dictionary
    int i,j,k,nCount;
    string s,c,str1,str2;
    ifstream infile("in.txt",ios::out);
    if(!infile)
    {
        cout<<"test文件不能打开"<<endl;
        return 0;
    }
    infile>>str1;
    i=0;
    while(str1[i])
    {
        dicts[i].str=str1[i];
        dicts[i].code=i+1;
        i++;
    }
    nCount=i;  //记录初始化的字典个数
    infile.close();
        //Input
    ifstream ifile("in1.txt",ios::out);
    ifile>>str2;
    i=0;
     bool flag=false;
     s=str2[i++];
    while(str2[i-1])  //要包括最后一个字符
    {
        string add_str;//存储 s+c
        c=str2[i];
        add_str+=s; add_str+=c;
        for(j=0; j<nCount; j++)
        {
               if(add_str==dicts[j].str)
               {
                   s=dicts[j].str;  //s=s+c
                   break;        
               }
        }
        if(j==nCount)
        {    //不在字典里
            for(k=0; k<nCount; k++)
             {  //output the code for s
                    if(dicts[k].str==s)
                    {       
                         cout<<dicts[k].code;
                         s=c;
                         break;
                    }
             }        
            //把s+c添加到字典里
              dicts[nCount].str=add_str;
              dicts[nCount].code=nCount+1;
               nCount++;
        }
        i++;
    } //while
    printf("\n");
    ifile.close();
    return 0;
}

 

 

posted @ 2012-04-10 21:05  Jason Damon  阅读(1901)  评论(0)    收藏  举报