Immediate Decodability |
An encoding of a set of symbols is said to be immediatelydecodable if no code for one symbol is the prefix of a code for another symbol. We will assume for this problem that all codes are in binary, that no two codes within a set of codes are the same, that each code has at least one bit and no more than ten bits, and that each set has at least two codes and no more than eight.
Examples: Assume an alphabet that has symbols {A, B, C, D}
The following code is immediately decodable:
A:01 B:10 C:0010 D:0000
but this one is not:
A:01 B:10 C:010 D:0000
(Note that A is a prefix of C)
Input
Write a program that accepts as input a series of groups of records from a data file. Each record in a group contains a collection of zeroes and ones representing a binary code for a different symbol. Each group is followed by a single separator record containing a single 9; the separator records are not part of the group. Each group is independent of other groups; the codes in one group are not related to codes in any other group (that is, each group is to be processed independently).
Output
For each group, your program should determine whether the codes in that group are immediately decodable, and should print a single output line giving the group number and stating whether the group is, or is not, immediately decodable.
The Sample Input describes the examples above.
Sample Input
01 10 0010 0000 9 01 10 010 0000 9
Sample Output
Set 1 is immediately decodable Set 2 is not immediately decodable
这题其实只要排一次虚就好了,因为如果一个串是另一个串的前缀,那么在用strcmp写的cmp函数排序下,前缀必然排在母串的前面。使用strstr时记得这是找子串而不是前缀,所以要考虑找
到的位置是否为第一个元素所在位置。
代码如下:
1 #include <cstdio>
2 #include <cstring>
3 #include <cstdlib>
4 using namespace std;
5
6 char num[200000][10];
7
8 bool getstr( char *s )
9 {
10 int p = 0;
11 char c;
12 while( c = getchar(), c == ' ' || c == '\n' || c == EOF )
13 {
14 if( c == EOF )
15 return false;
16 }
17 s[p++] = c;
18 while( c = getchar(), c == '0' || c == '1' )
19 s[p++] = c;
20 s[p] = '\0';
21 return true;
22 }
23
24 int cmp( const void *a, const void *b )
25 {
26 return strcmp( ( char * )a, ( char * )b );
27 }
28
29 int main( )
30 {
31 int tt = 1;
32 while( getstr( num[0] ) )
33 {
34 int k = 1, flag = 0;
35 while( getstr( num[k] ), num[k++][0] != '9' ) ;
36 qsort( num, k, sizeof( num[0] ), cmp );
37 for( int i = 0; i < k - 1; ++i )
38 {
39 char *pos;
40 if( ( pos = strstr( num[i+1], num[i] ) ) && pos == num[i+1] )
41 flag = 1;
42 }
43 if( !flag )
44 {
45 printf( "Set %d is immediately decodable\n", tt++ );
46 }
47 else
48 {
49 printf( "Set %d is not immediately decodable\n", tt++ );
50 }
51 }
52 }