字典树模板套用,判断一个单词是否为某一单词的前缀
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int MAX=3;
typedef struct TrieNode
{
int sign;
struct TrieNode *next[MAX];
} TrieNode;
TrieNode Memory[1000000];
int allocp = 0;
int fsign;
TrieNode * createTrieNode()
{
TrieNode * tmp = &Memory[allocp++];
tmp->sign = 0;
for (int i = 0; i < MAX; i++)
tmp->next[i] = NULL;
return tmp;
}
void insertTrie(TrieNode * * pRoot, char * str)
{
TrieNode * tmp = *pRoot;
int i = 0, k;
while (str[i])
{
k = str[i++] - '0';
if (tmp->next[k])
{
if(tmp->next[k]->sign==1||str[i]=='\0')
{
fsign=0;
return;
}
}
else
{
tmp->next[k] = createTrieNode();
}
tmp = tmp->next[k];
}
tmp->sign=1;
}
int main()
{
char s[15];
int t,n;
int i,j;
TrieNode *p;
t=1;
fsign=1;
allocp=0;
p=createTrieNode();
while(gets(s))
{
if(s[0]=='9')
{
if(fsign==1)
{
printf("Set %d is immediately decodable\n",t++);
}
else
{
printf("Set %d is not immediately decodable\n",t++);
}
allocp=0;
fsign=1;
p=createTrieNode();
}
else
{
if(fsign)
{
insertTrie(&p,s);
}
//printf("%s\n",s);
}
}
return 0;
}