Description
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
Output
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
解題思路
這題和phone list 那題是差不多的,
一個字符串不能是其他字符串的前綴,若存在輸出Set %d is not immediately decodable,否則輸出Set %d is immediately decodable
AC代碼
#include <cstdio>
#include <cstring>
int trie[1005][20], val[1005], num_jd, finish[1005][20], flag1, flag2, flag;
void init()
{
num_jd = 1;
memset(trie, 0, sizeof(trie));
memset(val, 0, sizeof(val));
memset(finish, 0, sizeof(finish));
flag = 0;
}
void insert(char *s)
{
int i, u = 0, c, len = strlen(s);
for(i = 0; i < len; i++)
{
c = s[i] - '0';
if(!trie[u][c])
{
trie[u][c] = num_jd++;
flag1 = 1;
}
if(finish[u][c])
flag2 = 1;
if(i == len - 1)
finish[u][c] = 1;
u = trie[u][c];
val[u]++;
}
}
int main()
{
int cas = 1;
char str[20];
init();
while(scanf("%s", str) != EOF)
{
if( flag && str[0] != '9' )
continue;
if( str[0] != '9' )
{
flag1 = flag2 = 0;
insert(str);
if( flag1 == 0 || flag2 == 1 )
flag = 1;
}
else
{
if( flag )
printf("Set %d is not immediately decodable\n", cas++);
else
printf("Set %d is immediately decodable\n", cas++);
init();
}
}
return 0;
}