传送门:hdu 1305 Immediate Decodability
题目大意
查询一个单词是不是另一个单词的前缀。
解题思路
简单地字典树题目!!
AC代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mst(a,b) memset(a,b,sizeof(a))
const int MAX = 3;
struct Node{
int flag;
Node *next[MAX];
Node()
{
flag = 0;
mst(next,NULL);
}
~Node()
{
for(int i=0;i<MAX;i++)
if(next[i]!=NULL)
delete next[i];
}
}TrieNode;
Node *root;
bool insert(char *str)
{
int len = strlen(str);
bool flag = true;
Node *p = root,*q;
for(int i=0;i<len;i++)
{
if(p->next[str[i]-'0'] == NULL)
{
q = new Node;
p->next[str[i]-'0'] = q;
flag = false;
}
if(p->flag == 1)
{
return true;
}
p=p->next[str[i]-'0'];
}
p->flag = 1;
return flag;
}
int main()
{
char str[150];
bool flag = false;
int cnt=1;
root =new Node;
while(~scanf("%s",str))
{
if(str[0] == '9')
{
if(flag) printf("Set %d is not immediately decodable\n",cnt++);
else printf("Set %d is immediately decodable\n",cnt++);
flag = false;
delete root;
root = new Node;
continue;
}
if(!flag)
flag = insert(str);
}
return 0;
}