【水题-前缀码】HDU 1305 Immediate Decodability

来源:互联网 发布:淘宝数据魔方论坛 编辑:程序博客网 时间:2024/05/01 04:22

1305 ( Immediate Decodability ) 


Problem Description

An encoding of a set of symbols is said to be immediately decodable if no code for one symbol is the prefix of a code for another symbol. We will assume for this problem that all codes are in binary, that no two codes within a set of codes are the same, that each code has at least one bit and no more than ten bits, and that each set has at least two codes and no more than eight.
Examples: Assume an alphabet that has symbols {A, B, C, D}
The following code is immediately decodable:
A:01 B:10 C:0010 D:0000
but this one is not:
A:01 B:10 C:010 D:0000 (Note that A is a prefix of C)

Input
Write a program that accepts as input a series of groups of records from input. Each record in a group contains a collection of zeroes and ones representing a binary code for a different symbol. Each group is followed by a single separator record containing a single 9; the separator records are not part of the group. Each group is independent of other groups; the codes in one group are not related to codes in any other group (that is, each group is to be processed independently).

Output
For each group, your program should determine whether the codes in that group are immediately decodable, and should print a single output line giving the group number and stating whether the group is, or is not, immediately decodable.

Sample Input
01
10
0010
0000
9
01
10
010
0000
9

Sample Output
Set 1 is immediately decodable

Set 2 is not immediately decodable


题目要求很简单,判断给定编码能否构成前缀码,也就是要求每一个编码都不是其他编码的前缀。最简单的方式当然是用一个编码和其他所有编码比较。这样做肯定可以AC,但是你想过还有其他更好的方法吗?还记得数据结构课上老师讲霍夫曼编码时提到的用二叉树可以构造出前缀码吗?没错,从根出发,到叶子节点的路径刚好是个前缀码。既然用二叉树可以构造前缀码,那么检测是否为前缀码也一定可以。我们根据给定编码,从根出发,找到相应的叶子节点,标记这个节点。如果另外一个编码用同样方法走,走到了一个被标记的节点,则说明出现冲突。二叉树可以用数组表示,访问起来更便捷。

(PS:编码要从短的到长的扫描才可以)


#include <iostream>#include <cstring>using namespace std;bool btree[2048];bool check(string& s){    int pos = 1;    for (int i = 0; i < s.size(); i++)    {        if (s[i] == '0')            pos *= 2;        else            pos *= 2, pos++;        if (btree[pos])            return false;    }    btree[pos] = true;    return true;}int main(){    string s;    int c = 0;    while (cin >> s)    {        memset(btree, false, sizeof(btree));        check(s);        int ok = true;        while (cin >> s)        {            if (s == "9")                break;            else if (ok && !check(s))                ok = false;        }        if (ok)            cout << "Set " << ++c << " is immediately decodable" << endl;        else            cout << "Set " << ++c << " is not immediately decodable" << endl;    }    return 0;}


0 0
原创粉丝点击