hdu 1053

这是题目的链接http://acm.hdu.edu.cn/showproblem.php?pid=1053

 

此题是一道很纯朴的哈夫曼树编码问题,但由于一个特殊的边界条件,贡献了一个wrong answer。

如果有做这题wa的同学可以试试以下这个测试数据:

 

Sample Input:

________

END

 

Sample Output:

64 8 8.0

 

#include #include #include using namespace std; const int inf = 1000000000; const int maxn = 27; const int bit = 8; struct node { bool is_used; int freq; int left, right; int key; }; node n[maxn]; int code[maxn]; node arr[maxn*maxn]; int cnt; int min(int beg, int end, int &min_key) { int ans = inf; for(int i = beg; i < end; i++) if(!arr[i].is_used && ans > arr[i].freq) { ans = arr[i].freq; min_key = i; } arr[min_key].is_used = true; return ans; } void build_tree() { int j = 0; for(int i = 0; i < maxn; i++) if(n[i].freq) arr[j++] = n[i]; for(int i = 0; i < cnt-1; i++) { int k = cnt + i; int m1, m1x; int m2, m2x; m1 = min(0, k, m1x); m2 = min(0, k, m2x); arr[k].left = m1x; arr[k].right = m2x; arr[k].freq = m1 + m2; } // cout << arr[cnt + cnt-1-1].freq << endl; } void dfs_tree(int idx, int level) { if(arr[idx].left == -1 && arr[idx].right == -1) code[arr[idx].key] = level; else { if(arr[idx].left != -1) dfs_tree(arr[idx].left, level+1); if(arr[idx].right != -1) dfs_tree(arr[idx].right, level+1); } } #define LOCAL int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif string input; while(cin >> input) { if(input == "END") break; memset(code, 0, sizeof(code)); for(int i = 0; i < maxn; i++) { n[i].is_used = false; n[i].freq = 0; n[i].left = n[i].right = -1; n[i].key = i; } for(int i = 0; i < maxn*maxn; i++) { arr[i].is_used = false; arr[i].freq = 0; arr[i].left = arr[i].right = -1; } cnt = 0; for(int i = 0; i < input.length(); i++) if(input[i] != '_') { if(n[input[i]-'A'].freq == 0) ++cnt; ++n[input[i]-'A'].freq; } else { if(n[maxn-1].freq == 0) ++cnt; ++n[maxn-1].freq; } int len1 = input.length() * bit; int len2 = 0; if(cnt == 1) //特殊边界条件的处理 len2 = input.length(); else { build_tree(); dfs_tree(cnt+cnt-1-1, 0); for(int i = 0; i < maxn; i++) len2 += code[i] * n[i].freq; } // printf("%d/n", len2); printf("%d %d %.1lf/n", len1, len2, (double)len1/len2); } return 0; }  

你可能感兴趣的:(hdu 1053)