思路:字典树
分析:
1 题目要求的是是否有一个字符串作为其它字符串的前缀
2 利用字典树的性质在插入的时候就可以判断某一个字符串是否是其它字符串或当前字符串是其它字符串的前缀
3 多组数据利用静态分配不能用动态分配。
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define MAXN 1000010
#define N 15
int cnt;
struct Trie{
bool flag;
Trie *child[N];
}trie[MAXN];
Trie *root;
/*静态分配空间*/
Trie* newTrie(){
trie[cnt].flag = false;
for(int i = 0 ; i < N ; i++)
trie[cnt].child[i] = NULL;
return &trie[cnt++];
}
/*字典树的插入*/
bool insert(char *str){
Trie *s = root;
int len = strlen(str);
for(int i = 0 ; i < len ; i++){
int num = str[i]-'0';
if(s->child[num] == NULL)
s->child[num] = newTrie();
s = s->child[num];
if(s->flag == true)
return false;
}
for(int i = 0 ; i < N ; i++){
if(s->child[i])
return false;
}
s->flag = true;
return true;
}
int main(){
int mark , Case;
char ch[N];
Case = 1;
while(scanf("%s" , ch) != EOF){
cnt = 0;
root = newTrie();
mark = 1;
if(!insert(ch))
mark = 0;
while(scanf("%s" , ch) && strcmp(ch , "9") != 0){
if(mark){
if(!insert(ch))
mark = 0;
}
}
if(mark)
printf("Set %d is immediately decodable\n" , Case++);
else
printf("Set %d is not immediately decodable\n" , Case++);
}
return 0;
}