Message Decoding(紫书例题 4-4)

题目其实已经说明了这一题的处理方式,

考虑下面的01串序列:
0, 00, 01, 10, 000, 001, 010, 011, 100, 101, 110, 0000, 0001, …, 1101, 1110, 00000, …
首先是长度为1的串,然后是长度为2的串,依此类推。如果看成二进制,相同长度的后
一个串等于前一个串加1。注意上述序列中不存在全为1的串。
你的任务是编写一个解码程序。首先输入一个编码头(例如AB#TANCnrtXc),则上述
序列的每个串依次对应编码头的每个字符。例如,0对应A,00对应B,01对应#,…,110对
应X,0000对应c。接下来是编码文本(可能由多行组成,你应当把它们拼成一个长长的01
串)。编码文本由多个小节组成,每个小节的前3个数字代表小节中每个编码的长度(用二
进制表示,例如010代表长度为2),然后是各个字符的编码,以全1结束(例如,编码长度
为2的小节以11结束)。编码文本以编码长度为000的小节结束

显然可以看成这样

0(0)

00(0) 01(1) 10(2) 

000(0) 001(1) 010(2) 011(3) 100(4) 101(5) 110(6) 

。。。

使用一个二维数组进行对应即可

按照紫书上说的是 使用一个 int code[][] 进行对应就可以了

然后就可以写出代码。(书上代码)

//#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <iostream>

#define mem(a,b) memset(a,b,sizeof(a))

using namespace std;

int code[8][1<<8];
int readchar()
{
	while(true)
	{
		int ch = getchar();
		if(ch != '\n' && ch != '\r')return ch;
	}
}
int readint(int c)
{
	int v = 0;
	while(c--)	v = v * 2 + readchar() - '0';
	return v;
}
int readcodes()
{
	mem(code,0);
	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; 
		}
	}
}
int main(void)
{

	while(readcodes())
	{
		for(;;)
		{
			int len = readint(3);
			if(len == 0)break;
			while(true)
			{
				int v = readint(len);
				if(v == (1<<len)-1)break;
				putchar(code[len][v]);
			}	
		}
		putchar('\n');
	}
		
	return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值