UVa 213:Message Decoding

题目传送门:https://cn.vjudge.net/problem/UVA-213

0, 00, 01, 10, 000, 001, 010, 011, 100, 101, 110, 0000, 0001, … , 1011, 1110, 00000, …

输入头对应的字符存储在 codes[len][value] 数组中(表示长度为len且编码为value的字符),例如:
codes[1][0] 代表 0 对应的 key
codes[2][0] 代表 00 对应的 key
codes[2][1] 代表 01 对应的 key
codes[2][2] 代表 10 对应的 key
codes[3][0] 代表 000 对应的 key

AC代码:

#include <stdio.h>
#include <memory.h>
char codes[8][130]; // 用于保存编码的字符

int readChar() { // 读取一个字符,注意剔除回车和换行
    while (true) {
        int ch = getchar();
        if (ch != '\n' && ch != '\r')
            return ch;
    }
}

int readInt(int len) { // 读取二进制字符串,len为长度,返回对应的十进制数
    int digit = 0;
    while (len--)
        digit = 2 * digit + readChar() - '0';
    return digit;
}

int readHeader() { // 读取编码头
    memset(codes, 0, sizeof(codes));
    codes[1][0] = readChar(); // 先读取一个看是不是EOF
    if (EOF == codes[1][0])
        return 0;

    for (int len = 2; len <= 7; ++len) {
        for (int i = 0; i < (1 << len) - 1; ++i) {
            int ch = getchar();
            if (EOF == ch) return 0;
            if ('\n' == ch || '\r' == ch) return 1;
            codes[len][i] = ch;
        }
    }

    return 1;
}

void printCodes() {
    for (int len = 1; len <= 7; ++len) {
        for (int i = 0; i < (1 << len) - 1; ++i)
            putchar(codes[len][i]);
        putchar('\n');
    }
}

int main()
{
    while (readHeader()) {
        //printCodes();
        while (true) {
            int len = readInt(3);
            if (0 == len) break;
            while (true) {
                int x = readInt(len);
                if (x == (1 << len) - 1) break;
                putchar(codes[len][x]);
            }
        }
        putchar('\n');
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值