[算法竞赛入门经典]Message Decoding,ACM/ICPC World Finals 1991,UVa213

Description

Some message encoding schemes require that an encoded message be sent in two parts. The first part, called the header, contains the characters of the message. The second part contains a pattern that represents the message. You must write a program that can decode messages under such a scheme.
The heart of the encoding scheme for your program is a sequence of “key” strings of 0’s and 1’s as follows:
0, 00, 01, 10, 000, 001, 010, 011, 100, 101, 110, 0000, 0001, . . . , 1011, 1110, 00000, . . .
The first key in the sequence is of length 1, the next 3 are of length 2, the next 7 of length 3, the next 15 of length 4, etc. If two adjacent keys have the same length, the second can be obtained from the first by adding 1 (base 2). Notice that there are no keys in the sequence that consist only of 1’s.
The keys are mapped to the characters in the header in order. That is, the first key (0) is mapped to the first character in the header, the second key (00) to the second character in the header, the kth key is mapped to the kth character in the header. For example, suppose the header is:
AB#TANCnrtXc
Then 0 is mapped to A, 00 to B, 01 to #, 10 to T, 000 to A, ..., 110 to X, and 0000 to c.
The encoded message contains only 0’s and 1’s and possibly carriage returns, which are to be ignored. The message is divided into segments. The first 3 digits of a segment give the binary representation of the length of the keys in the segment. For example, if the first 3 digits are 010, then the remainder of the segment consists of keys of length 2 (00, 01, or 10). The end of the segment is a string of 1’s which is the same length as the length of the keys in the segment. So a segment of keys of length 2 is terminated by 11. The entire encoded message is terminated by 000 (which would signify a segment in which the keys have length 0). The message is decoded by translating the keys in the segments one-at-a-time into the header characters to which they have been mapped.

Input

The input file contains several data sets. Each data set consists of a header, which is on a single line by itself, and a message, which may extend over several lines. The length of the header is limited only by the fact that key strings have a maximum length of 7 (111 in binary). If there are multiple copies of a character in a header, then several keys will map to that character. The encoded message contains only 0’s and 1’s, and it is a legitimate encoding according to the described scheme. That is, the message segments begin with the 3-digit length sequence and end with the appropriate sequence of 1’s. The keys in any given segment are all of the same length, and they all correspond to characters in the header. The message is terminated by 000.
Carriage returns may appear anywhere within the message part. They are not to be considered as part of the message.

Output

For each data set, your program must write its decoded message on a separate line. There should not be blank lines between messages.

Sample input

TNM AEIOU
0010101100011
1010001001110110011
11000
$# 0100000101101100011100101000

Sample output

TAN ME ##*$

Analyze

看紫书的时候卡在这题老久了,题目倒是看懂了,但是刘老师的代码前几眼实在是有点抽象,不过懂了之后确实感觉很巧妙。
题目会给你二进制递增(在各自的位数里递增)序列,然后先输入一串你自定义的编码头,将这个串的每个字符和二进制序列的每个数建立映射,再根据后面输入的编码按要求一一对应输出。

什么是各自的位数呢,比如:
1位: 0
2位: 00 01
3位: 000 001 010 011 100 101 110 111
...
将它们写在一行就是:

0,00,01,10,000,001,010,011,100,101,110,111,0000, . . . (无限长)

假设编码头是AB#TANC,那么映射是这样的:

0   00   01   10   000   001   010
A    B     #     T    A    N    C

编码的读入要求就不用我多说了吧。

解读一下核心readCodes函数:

readCodes()函数,作用是读取每组数据首行的编码头

int readCodes() {
    memset(code, 0, sizeof(code));
    code[1][0] = readChar();        // 先把编码头的第一个字母读进来
    for(int len = 2; len <= 7; len++) { 
        for(int i = 0; i < (1 << len) - 1; i++) {
            int ch = getchar();
            // 文件结束,终止程序
            if(ch == EOF) {
                return 0;
            }
            // 读一行
            if(ch == '\n' || ch == '\r') {
                return 1;
            }
            code[len][i] = ch;
        }
    }
    return 1;
}

怎么理解readCodes()呢?之前列举的编码头AB#TANC对应的映射二进制数是

0 00 01 10 000 001 010
位数: 1 2 2 2 3 3 3

可以看到1位二进制的只有0一种情况,不用循环处理,所以直接由code[1][0] = readChar();读金第一个字符。

你会问为什么不从code[0][0]开始呢?因为仅从自然语义来说更容易操作,假设1位就写code[1][xxx]而不是code[0][xxx]。

从二位的二进制数开始,每种位(n)二进制数的组合就有2^n-1种(为什么不是2^n种呢,因为题目要求后面输入的编码全为1的代表结束,所以和编码头映射时全为1的编码无任何意义,直接舍弃)。

所以我们会发现函数中的第二层循环for(int i = 0; i < (1 << len) - 1; i++)算的正是每种位二进制数所有的取值对应的10进制数,并将算出的i映射到code数组的第二个维度下标上。

而第一层循环负责控制二进制位数的范围。

就之前的例子来说,AB#TANC映射到数组里是这样的:

位数为2的映射: code[2][0(00)] = B的asc2值 code[2][1(01)] = # 的asc2值 code[2][2(10)] = T的asc值
位数为3的映射: code[3][0(000)] = A的asc2值 code[3][1(001)] = N的asc2值 code[3][2(010)] = C的asc值

我觉得我解释得够详细了吧?难点几乎就是在这了

Code

#include <stdio.h>
#include <string.h>
int code[8][1<<8];
int readChar() {
    while(true) {
        int ch = getchar();
        // 读到非换行符为止
        if(ch != '\n' && ch != '\r') {
            return ch;
        }
    }
}
int readInt(int c) {    //将指定的下c位二进制转换为10进制
    int v = 0;
    while(c--) {
        v = v * 2 + readChar() - '0';
    }
    return v;
}

int readCodes() {
    memset(code, 0, sizeof(code));
    // 读取编码头的第一个字符
    code[1][0] = readChar();
    for(int len = 2; len <= 7; len++) {
        for(int i = 0; i < (1 << len) - 1; i++) {
            int ch = getchar();
            if(ch == EOF) {
                return 0;
            }
            if(ch == '\n' || ch == '\r') {
                return 1;
            }
            code[len][i] = ch;
        }
    }
    return 1;
}

int main() {
    while(readCodes()) {    //读编码头
        while(true) {
            int len = readInt(3);
            if(!len) {
                break;
            }
            while(true) {           //读编码
                int v = readInt(len);
                if(v == (1 << len) - 1) {
                    break;
                }
                putchar(code[len][v]);
            }
        }
        putchar('\n');
    }
    return 0;
}

转载于:https://www.cnblogs.com/1Kasshole/p/9726248.html

<think>好的,用户遇到了一个关于MessagePack解码的错误:'invalid code=d2 decoding string/bytes length'。我需要先理解这个错误的原因,然后找到解决方法。 首先,我应该回顾MessagePack的编码格式。根据引用[3],MessagePack使用二进制格式,不同的数据类型有不同的前缀码。比如,小整数可能用单字节,而字符串可能有不同的前缀表示长度。错误信息中的code=d2是十六进制的D2,对应十进制的210。不过MessagePack的格式规范中,前缀码通常有特定的范围。例如,fixstr类型的前缀码范围是0xA0到0xBF,表示长度不超过31的字符串。当处理字符串或二进制数据时,编码器会使用不同的前缀码,如0xD9表示后面跟着一个8位长度,0xDA表示16位,0xDB表示32位。而D2对应的十进制是210,可能属于保留或未定义的范围,或者可能属于其他数据类型的前缀码。 用户提供的引用[2]中的代码示例显示,他们写入的字节数组包含0xA4,这是fixstr类型,长度为4(0xA4 - 0xA0 = 4),后面跟着“abcd”。但如果数据中包含0xD2,这可能是问题所在。例如,如果编码时错误地将字符串长度标识为0xD2,而解码器期望的是字符串或二进制数据的有效前缀码,就会报错,因为0xD2实际上对应的是int16类型的前缀码。也就是说,解码器在尝试读取字符串或字节数组时遇到了一个表示int16的前缀码,导致类型不匹配,从而引发错误。 可能的原因是数据在编码过程中被错误地序列化,例如将整数类型的数据错误地标记为字符串,或者在处理二进制数据时使用了错误的前缀码。例如,编码器可能错误地使用了0xD2(表示int16)来标识字符串的长度,而解码器期望的是字符串的前缀码(如0xD9、0xDA、0xDB),因此无法正确解析长度字段,导致'invalid code'错误。 解决方法需要检查编码和解码的代码,确保数据类型和前缀码一致。用户需要确认编码端是否正确处理了字符串或二进制数据,使用了正确的格式。例如,对于较长的字符串,应该使用0xD9、0xDA或0xDB作为前缀,后面跟随相应的长度字段和数据内容。如果编码端错误地使用了其他类型的前缀码,如0xD2,解码时就会失败。 另外,用户提供的引用[2]中的示例代码写入的字节数组包含0xA4,这是正确的字符串前缀码。但如果实际数据中存在0xD2,就需要检查这些数据是如何生成的。可能是在编码过程中混入了其他数据类型,或者在处理数据时出现了字节错位,导致解码器读取了错误的前缀码。 总结,根本原因可能是编码端使用了不正确的类型标识符,导致解码器无法识别。用户需要检查编码逻辑,确保字符串或二进制数据使用正确的前缀码,并验证数据流的完整性,避免数据损坏或格式错误。</think>### MsgPack错误'invalid code=d2 decoding string/bytes length'原因与解决方案 #### 错误原因分析 1. **编码格式不匹配** MessagePack中`0xD2`是16位有符号整型(int16)的标识符[^3]。当解码器期望读取字符串或二进制数据(如`str`/`bin`类型)时,若遇到`0xD2`前缀,会因类型不匹配触发该错误。例如: $$ \text{str类型标识符范围} = \begin{cases} 0xA0 \sim 0xBF & \text{fixstr(长度≤31)} \\ 0xD9 & \text{str8(长度≤255)} \\ 0xDA & \text{str16(长度≤65535)} \\ 0xDB & \text{str32(长度≤4294967295)} \end{cases} $$ 2. **数据流损坏或编码错误** 若编码端错误地将整数类型写入字符串字段(如将`int16`数据误标记为`str`),或网络传输中发生字节错位,会导致解码器解析失败[^2]。 #### 解决步骤 1. **验证编码逻辑** 检查编码端是否对字符串/二进制字段使用正确标识符: ```python # Python示例:正确编码字符串 import msgpack data = {"key": "value"} packed = msgpack.packb(data, use_bin_type=True) # 确保启用bin类型 ``` 2. **检查数据完整性** 使用十六进制查看工具(如`hexdump`)验证原始字节流: ```bash hexdump -C your_data.msgpack ``` 若发现非预期的`0xD2`字节,需排查编码端逻辑或数据传输过程。 3. **兼容性处理** 在解码端添加容错机制,捕获异常并记录上下文: ```go // Go示例:带错误处理的解码 dec := msgpack.NewDecoder(buf) for { out, err := dec.DecodeBytes() if err != nil { if strings.Contains(err.Error(), "invalid code=d2") { log.Printf("解码错误:数据包含非法类型标识符,位置=%d", dec.Buffered().Len()) } break } fmt.Println(string(out)) } ``` #### 相关引用说明 - 引用[3]指出MessagePack通过前缀码区分数据类型,如`0xD2`专用于int16[^3]。 - 引用[2]的代码演示了字节流操作中若包含非法标识符可能引发解码中断。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值