HDOJ 1305 Immediate Decodability(trie树入门)
题意:
即判断某一个字符串是否为其他字符串的前缀。
思路:
字典树。每个单词增加一个标记,表示这个字典是否是一个单词。
下次输入的时候就可以提前判断了。
#include <iostream>
using namespace std;
struct node {
bool isword;
int child[2];
} trie[1100] ;
int size = 0;
bool flag = false;
void Insert(char* word, int i, int rt)
{
if (!word[i])
{
trie[rt].isword = true;
return ;
}
int m = word[i] - '0';
if (trie[rt].child[m])
{
if (trie[trie[rt].child[m]].isword || !word[i+1])
flag = true;
Insert(word, i + 1, trie[rt].child[m]);
}
else
{
trie[rt].child[m] = ++size;
Insert(word, i + 1, size);
}
}
int main()
{
char word[12];
int cases = 0;
while (scanf("%s", word) != EOF)
{
if (word[0] == '9')
{
if (flag)
printf("Set %d is not immediately decodable\n", ++cases);
else
printf("Set %d is immediately decodable\n", ++cases);
size = 0;
flag = false;
memset(trie, 0, sizeof(trie));
continue;
}
Insert(word, 0, 0);
}
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------