UVa213 - Message Decoding

题意:给出一个字符串及其编码序列,解码得到原始序列。编码序列是用的二进制。形式如0,00,01,10。也就是根据二进制的位数及其所能表示的二进制,注意全1的不包含在内。0对应字符串的第一个字符,00对应字符串中的第二个字符。

思路:先建序列对应位置的表。其递推关系为f(1)= 0,f(2)= f(1) + 2^1 - 1,,,依此类推有f(n) = f(n-1) + 2^(n - 1) - 1。其它的就是根据题意来做。前三个字符表示后序key的长度。三个0表示结束。

代码如下:

#include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;

const int N = 8;

int f[N];

void init();
int binToInt(string s);

int main()
{
#ifndef ONLINE_JUDGE
	ifstream fin("F:\\OJ\\uva_in.txt");
	streambuf *old = cin.rdbuf(fin.rdbuf());
#endif

	init();
	string message;
	char ch;

	while (getline(cin, message))
	{
		while (1)
		{
			string str_len;
			int cnt = 0;
			while (cnt != 3)
			{
				cin.get(ch);
				
				if (ch == '\n') continue;
				str_len += ch;
				cnt++;
			}

			if (str_len == "000")
			{
				cout << endl;
				getline(cin, message);
				break;
			}

			int len = binToInt(str_len);
			while (1)
			{
				string tmp;
				int count = 0;
				while (count < len)
				{
					cin.get(ch);
					if (ch == '\n') continue;
					tmp += ch;
					count++;
				}

				string cmp;
				cmp.append(len, '1');
				if (tmp == cmp) break;

				int value = binToInt(tmp);
				int pos = f[len] + value;
				cout << message[pos];
			}
		}

	}

#ifndef ONLINE_JUDGE
	cin.rdbuf(old);
#endif

	return 0;
}

void init()
{
	f[0] = 0; f[1] = 0;
	for (int i = 2; i < N; i++)
	{
		f[i] = f[i - 1] + pow(2, i - 1) - 1;
	}
}

int binToInt(string s)
{
	int len = s.length();

	int sum = 0;
	for (int i = 0; i < len; i++)
	{
		sum = sum * 2 + (s[i] - '0');
	}

	return sum;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值