问题描述
- 为什么下面的代码没有达到我输出的要求,请大家帮忙看看吧,谢谢大家了!!
-
#include <iostream> #include <string> using namespace std; //#define MaxValue 10000; //初始设定的权值最大值 //#define MaxBit 4; //初始设定的最大编码位数 //#define Max 20 //初始设定的最大结点个数 struct HaffNode //哈夫曼树的结点结构 { string data; int weight; //权值 int flag; //标记 int parent; //双亲结点下标 int leftChild; //左孩子下标 int rightChild; //右孩子下标 }; struct Code //存放哈夫曼编码的数据元素结构 { int bit[]; //数组 int start; //编码的起始下标 int weight; //字符的权值 }; void Haffman( int n, HaffNode haffTree[]) //建立叶结点个数为n权值为weight的哈夫曼树haffTree { int j, m1, m2, x1, x2; //哈夫曼树haffTree初始化。n个叶结点的哈夫曼树共有2n-1个结点 for(int i = 0; i < 2 * n - 1 ; i++) { haffTree[i].weight = 0; haffTree[i].parent = 0; haffTree[i].flag = 0; haffTree[i].leftChild = -1; haffTree[i].rightChild = -1; } //构造哈夫曼树haffTree的n-1个非叶结点 for(int i = 0;i < n-1;i++) { m1 = m2 = n; x1 = x2 = 0; for(j = 0; j < n+i;j++)//找出剩下的两个比较小的节点 { if (haffTree[j].weight < m1 && haffTree[j].flag == 0) { m2 = m1; x2 = x1; m1 = haffTree[j].weight; x1 = j; } else if(haffTree[j].weight < m2 && haffTree[j].flag == 0) { m2 = haffTree[j].weight; x2 = j; } } //将找出的两棵权值最小的子树合并为一棵子树 haffTree[x1].parent = n+i; haffTree[x2].parent = n+i; haffTree[x1].flag = 1; haffTree[x2].flag = 1; haffTree[n+i].weight = haffTree[x1].weight+haffTree[x2].weight; haffTree[n+i].leftChild = x1; haffTree[n+i].rightChild = x2; } } void dayin(HaffNode haffTree[],int k ,int n) { if(k==0) { return; } for (int i=0;i<n;i++) { cout<<" "; } if(haffTree[k].parent!=-1) { cout<<"|_"; } else { cout<<" "; } cout<<haffTree[k].data<<endl; int L=haffTree[k].leftChild; int R=haffTree[k].rightChild; dayin(haffTree,R,n+2); dayin(haffTree,L,n+2); } void HaffmanCode(string *s,int *w) //由n个结点的哈夫曼树haffTree构造哈夫曼编码haffCode { int i,k,n; HaffNode haffTree[2*n-1]; Code cd[2*n-1]; int child; int parent; //求n个叶结点的哈夫曼编码 for(int i = 0; i < n; i++) { cd->start = n-1; //不等长编码的最后一位为Max-1 cd->weight = haffTree[i].weight; //取得编码对应权值的字符 child=i; parent = haffTree[child].parent; //由叶结点向上直到根结点 while(parent != 0) { if(haffTree[parent].leftChild == child) cd->bit[cd->start] = 0; //左孩子结点编码0 else cd->bit[cd->start] = 1;//右孩子结点编码1 cd->start--; child = parent; parent = haffTree[child].parent; } } Haffman( 0, haffTree); cout<<"输出哈夫曼码:"; for(i=1;i<=n;i++) { cout<<haffTree[i].data<<": "; for(k=cd[i].start;k<=n;k++) cout<<cd[i].bit[k]; cout<<endl; } for(i=0;i<2*n-1;i++) { if(haffTree[i].flag==0) dayin(haffTree,2*n-1,0); cout<<endl; } } int main(int argc, char *argv[]) { int i, j,n ; cout<<"输入字符个数: "; cin>>n; string* s = new string[n]; int* w = new int[n]; for(i=0;i<=n;i++) { cout<<"请输入字符:"; cin>>s[i]; cout<<"请输入权值: "; cin>>w[i]; } HaffmanCode(s,w); return 0; }
我输入2个字符数的时候,输入完了2个字符和权值下面还提示输入字符,不是应该打印和编码我输入的哈夫曼树了吗,哪里错了,请大家指出,并帮我看看吧,谢谢!!
解决方案
for(i=0;i<=n;i++)
这种情况输入n+1个
把<=改为<
解决方案二:
请各位能人帮忙!!把下面的delphi代码翻译成VC++,感激不尽。。。。。。。
解决方案三:
支持下,
虽然看不出
时间: 2024-11-05 06:06:27