Tips:注意二进制读写文件回车为:
代码详细分析改天再填坑。。。
还有单纯形算法--> github:https://github.com/caitian521/algorithm
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <iostream> #include <list> #include <string> using namespace std; template<class Type> struct huffnode{ int weight; Type ch; char code[50]; int parent,leftchild,rightchild; public: huffnode():ch(Type()),weight(0),parent(-1),leftchild(-1),rightchild(-1) {} }; class hufftree { list<huffnode<char> > hufflist; huffnode<char> *nodetable; char file[200]; int num; public: hufftree(const char *filename); ~hufftree(); void Addchar(const char s); void CreateTree(); bool SelectMin(const int pos,int &minst); void CreateCode(); void Compression(); void showcode(); void CreateConfig(); void Decompression(); int Match(const char prebuff[],const char buff[],int &endat,FILE *fout,int &cnt); void print(int p,FILE *fout,int &cnt); }; hufftree::hufftree(const char *filename) { strcpy(file,filename); FILE *fin1 = fopen(file,"rb"); char s; s = fgetc(fin1); while(s !=EOF) { if(s==' ') s = fgetc(fin1); Addchar(s); s = fgetc(fin1); } num = hufflist.size(); printf("%d ",num); nodetable = new huffnode<char>[num*2-1]; list<huffnode<char> >::iterator iter = hufflist.begin(); for(int i = 0;i<num && iter!=hufflist.end();i++,iter++) { nodetable[i].ch = iter->ch; nodetable[i].weight = iter->weight; } fclose(fin1); } void hufftree::Addchar(const char s) { list<huffnode<char> >::iterator iter = hufflist.begin(); for(;iter!=hufflist.end();iter++) { if(iter->ch==s) { iter->weight++; break; } } if(iter==hufflist.end()) { huffnode<char> node; node.weight = 1; node.ch = s; hufflist.push_back(node); } } void hufftree::CreateTree() { int left = 0,right=0; for(int i = num;i<2*num-1;i++) { SelectMin(i-1,left); nodetable[left].parent = i; SelectMin(i-1,right); nodetable[right].parent = i; nodetable[i].weight = nodetable[left].weight+nodetable[right].weight; nodetable[i].leftchild = left; nodetable[i].rightchild = right; } } bool hufftree::SelectMin(const int pos,int &minst) { int i=0,minnum=0; while(minnum<pos) { if(nodetable[i].parent==-1) break; minnum++; } if(minnum>pos)//上一个while的目的 return false;//ruguo false??? while(i<=pos) { if(nodetable[i].parent == -1 && nodetable[minnum].weight>nodetable[i].weight) minnum = i; i++; } minst = minnum; } void hufftree::CreateCode() { int i; int c,p; int start; char *tmpcode = new char[num]; tmpcode[num] = '