题目:
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
有多个集合,如果当前集合的元素中,存在一个元素是另外一个元素的前缀,则是not immediately decodable,否则是immediately decodable,用字典树ok。
AC代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <queue>
#define maxn 405
#define INF 999999999
#define LL long long
using namespace std;
int root;
int Next[4000][3];
int p;
int sum[4000];//记录标点的个数
int Newnode()
{
for (int i = 0; i < 3; i++)
Next[p][i] = -1;
sum[p++]=0;
return p - 1;
}
void init()
{
memset(Next, 0, sizeof(Next));
memset(sum, 0, sizeof(sum));
p = 0;
root = Newnode();
}
void insert(char *x)
{
int len = strlen(x);
int u = root;
for (int i = 0; i < len; i++)
{
int c = x[i] - '0';
if (Next[u][c] == -1)
Next[u][c] = Newnode();
u = Next[u][c];
sum[u]++;
}
}
bool find(char *s)
{
int u = root;
int len = strlen(s);
for (int i = 0; i < len; i++)
{
int c = s[i] - '0';
u = Next[u][c];
if (sum[u] == 1)//标点个数为1时,说明这个单词不存在前缀
return 1;
}
return 0;
}
int b;
int main()
{
char aa[10][100];
int ans = 0;
init();
int cnt = 0;
while (scanf("%s", &aa[cnt])!=EOF)
{
if (aa[cnt][0] != '9')
{
insert(aa[cnt]);
cnt++;
}
else
{
int f = 0;
for (int i = 0; i < cnt; i++)
if (!find(aa[i]))
{
f = 1;
}
if (f == 0)
printf("Set %d is immediately decodable\n", ++ans);
else
printf("Set %d is not immediately decodable\n", ++ans);
cnt = 0;
init();
}
}
}