题目:给你一些01串,判断是不是某些串是其它串的前缀。
分析:字符串,字典树。
首先,将字符串按长度排序,这样前缀一定在前面;
然后,再插入字典树的过程中,判断是否覆盖即可。
说明:注意数组的大小。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
char words[1004][104];
/* Trie define */
#define nodesize 20002 //节点个数
#define dictsize 2 //字符集大小
typedef struct node1
{
int flag; //值域
node1* next[dictsize];
}tnode;
tnode dict[nodesize];
int ID[256];
class Trie
{
private:
int sub;
int size;
int count;
tnode* root;
public:
Trie() {makeID(); initial();}
void makeID() {ID['0'] = 0;ID['1'] = 1;}
void initial() {
memset( dict, 0, sizeof( dict ) );
count=0;size=0;sub=0;root=newnode();
}
tnode* newnode() {return &dict[size ++];}
void insert( char* word ) {
tnode* now = root;
for ( int i = 0 ; word[i] ; ++ i ) {
if ( !now->next[ID[word[i]]] )
now->next[ID[word[i]]] = newnode();
if ( now->flag ) sub = 1;
now = now->next[ID[word[i]]];
}
if ( now->flag ++ ) sub = 1;
}
int query() {return sub;}
}trie;
/* Trie end */
int cmp( const void* a, const void *b )
{
return strlen((char *)a) - strlen((char *)b);
}
int main()
{
int Case = 1;
while ( ~scanf("%s",words[0]) ) {
trie.initial();
int count = 1;
while ( words[count-1][0] != '9' )
scanf("%s",words[count ++]);
qsort( words, count-1, sizeof(words[0]), cmp );
for ( int i = 0 ; i < count-1 ; ++ i )
trie.insert( words[i] );
printf("Set %d is ",Case ++);
if ( trie.query() ) printf("not ");
printf("immediately decodable\n");
}
return 0;
}