/* 简单字典树 hdu 1251
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int MAX = 26;
struct node
{
int count ;//记录以该节点为前缀的字符串共出现的次数
struct node *next[MAX];
};
struct node *root;//根节点
struct node *build()//建树
{
node *p;
p=(struct node *)malloc(sizeof(struct node));
for(int i = 0; i < 26; i++)
{
p->next[i] = NULL;
}
p->count = 1;//初始化
return p;
}
void Insert(char *s)//插入
{
int len = strlen(s);
if(len==0) return ;
node *p;
p = root;
for(int i = 0; i < len; i++)
{
if(p->next[s[i]-'a']!=NULL)
{
p = p->next[s[i]-'a'];
p->count++;
}
else
{
p->next[s[i]-'a'] = build();
p = p->next[s[i]-'a'];
}
}
}
int Query(char *s)//查找
{
int len = strlen(s);
if(len==0) return 0;
node *p;
p = root;
for(int i = 0; i < len; i++)
{
if(p->next[s[i]-'a']!=NULL)
p = p->next[s[i]-'a'];
else return 0;
}
return p->count;
}
void Release(node *p)//释放空间
{
if(p==NULL)
return ;
for(int i = 0; i < MAX; i++)
{
if(p->next[i]!=NULL)
Release(p->next[i]);
}
free(p);
return ;
}
int main()
{
char str[11];
root = build();
while(gets(str)&&str[0]!='\0')
Insert(str);
while(~scanf("%s",str))
{
printf("%d\n",Query(str));
}
Release(root);
return 0;
}
1671
/*字典树 hdu 1671
判断在给出的n个字符串中是否存在一些字符串是其他字符串的子串
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
const int MAX = 10;
struct node
{
int count ;
struct node *next[MAX];
};
struct node *root;
struct node *build()//建树
{
node *p;
p=(struct node *)malloc(sizeof(struct node));
for(int i = 0; i < 10; i++)
{
p->next[i] = NULL;
}
p->count = -1;//初始化为-1
return p;
}
int Insert(char *s)//插入
{
int len = strlen(s);
node *p;
p = root;
bool flag = true;
for(int i = 0; i < len; i++)
{
if(p->next[s[i]-'0']!=NULL)
{
if(i==len-1)flag = false;//该串是之前插入字符串的子串
p = p->next[s[i]-'0'];
if(p->count==1)//之前插入的字符串是该串的子串
return 0;
}
else
{
p->next[s[i]-'0'] = build();
p = p->next[s[i]-'0'];
}
}
p->count = 1;
if(flag)
return 1;
else return 0;
}
void Release(node *p)//释放空间
{
if(p==NULL)
return ;
for(int i = 0; i < MAX; i++)
{
if(p->next[i]!=NULL)
Release(p->next[i]);
}
free(p);
return ;
}
int main()
{
char str[20];
int t,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
getchar();
root = build();
bool flag = true;
for(int i = 0; i < n; i++)
{
gets(str);
if(flag)
{
if(Insert(str)==0)
{
flag = false;
}
}
}
if(flag) puts("YES");
else puts("NO");
Release(root);
}
return 0;
}