UVa 213 - Message Decoding

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

特別注意指令(01…) 可能會跨行。

Solution

可以先把一些常用的常數記下來。讀取 '\n' 也要特別小心。
主要在於處理二進位轉成十進位後,依照其字串的長度加上 bias ( map[] ),還有處理全 1 的狀況。

Code

UVa 213
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<cstdio>
#include<cstring>

int exp2[8] = { 0,1,3,7,15,31,63,127 };//2^1-1,2^2-1,2^3-1,...
int map[7] = { 0,1,4,11,26,57,120 };//1+3+7+15+31+63+127
inline int hash(char *str)
{
int len = strlen(str);
int num = 0;
//二進位轉十進位
for (int i = 0; i < len; i++)
{
num <<= 1;
num += str[i] - '0';
}

if (num == exp2[len])//全1的狀況
return -1;
else
return num + map[len - 1];//對應到 header 的 idx
}
inline char readChar()
{
char c;
while ((c = getchar()) == '\n');

return c;
}
inline bool getHead(char *str)
{
char c;
int idx = 0;
c = readChar();

if (c == EOF)
return false;

str[idx++] = c;

while ((c = getchar()) != '\n')
str[idx++] = c;

str[idx] = NULL;
return true;
}
inline int getLen()
{
char c;
int num = 0;
//二進位轉十進位
for (int i = 0; i < 3; i++)
{
c = readChar();
num <<= 1;
num += c - '0';
}

return num;
}
int main()
{
char str[300];
while (getHead(str))
{
int len, i;
char c, code[10];
while (len = getLen())
{
while (true)
{
for (i = 0; i < len; i++)
{
c = readChar();
code[i] = c;
}

code[i] = NULL;
int val = hash(code);
if (val == -1)
break;

putchar(str[val]);
}
}

putchar('\n');
}

return 0;
}