字典树
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
遇到单词不认识怎么办? 查字典啊,已知字典中有n个单词,假设单词都是由小写字母组成。现有m个不认识的单词,询问这m个单词是否出现在字典中。
Input
含有多组测试用例。
第一行输入n,m (n>=0&&n<=100000&&m>=0&&m<=100000)分别是字典中存在的n个单词和要查询的m个单词.
紧跟着n行,代表字典中存在的单词。
然后m行,要查询的m个单词
n=0&&m=0 程序结束
数据保证所有的单词都是有小写字母组成,并且长度不超过10
Output
若存在则输出Yes,不存在输出No .
Example Input
3 2
aab
aa
ad
ac
ad
0 0
Example Output
No
Yes
Hint
Author
gyx
#include<iostream>
#include<string.h>
#include<stdlib.h>
#include<cstdio>
using namespace std;
struct node
{
int cnt;
struct node*next[26];
}tree[1000000];//建立静态节点数组
int top;
struct node*create()
{
struct node*p=&tree[top++];
p->cnt=0;
for(int i=0;i<26;i++)
{
p->next[i]=NULL;
}
return p;
};
struct node* InitBtTree()//初始化字典树
{
top=0;
return create();
}
void InsertTree(char a[],struct node*root)//在字典树中插入字符串
{
struct node*p=root;
for(int i=0;a[i]!='\0';i++)
{
int x=a[i]-'a';
if(p->next[x]==NULL)
p->next[x]=create();
p=p->next[x];
}
p->cnt++;
}
bool Find(struct node*root,char a[])//在字典树中查找字符串,并返回字符串的数量
{
int i;
struct node*p=root;
for(i=0;a[i]!='\0';i++)
{
int x=a[i]-'a';
if(p->next[x]==NULL)
return false;
p=p->next[x];
}
return true;
}
int main()
{
int n,m,i;
char a[15];
struct node*root;
while(scanf("%d%d",&n,&m)&&(n||m))
{
root=InitBtTree();
for(i=1;i<=n;i++)
{
scanf("%s",a);
InsertTree(a,root);
}
while(m--)
{
scanf("%s",a);
if(Find(root,a))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}
例题
迷之好奇
Problem Description
FF得到了一个有n个数字的集合。不要问我为什么,有钱,任性。
FF很好奇的想知道,对于数字x,集合中有多少个数字可以在x前面添加任意数字得到。
如,x = 123,则在x前面添加数字可以得到4123,5123等。
input
多组输入。
对于每组数据
首先输入n(1<= n <= 100000)。
接下来n行。每行一个数字y(1 <= y <= 100000)代表集合中的元素。
接下来一行输入m(1 <= m <= 100000),代表有m次询问。
接下来的m行。
每行一个正整数x(1 <= x <= 100000)。
Sample Input
3
12345
66666
12356
3
45
12345
356
Sample Output
1
0
1
分析:
本题数据数据量较大,显然是不可以用常用方法解决的,这时候就可以用字典树,我们可以让字典树的每一个节点储存一个数字,我们从后往前插入数字,并使p->cnt++(表示在这个集合中这一位的数字的个数加一)例如12345插入的时候3在第三层插入并使这一层这个节点加一,在再插入2345时候由于这个节点已经开辟了,我们在遍历过程中经过了这个节点 便使其加一表示以345为后缀的数已经有两个了,这样我们在查询345的时候 我们遍历到3的时后p->cnt的值就是以345为后缀的数字的个数
#include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
using namespace std;
struct node
{
int data;
struct node*next[26];
}tree[200000];
int top;
struct node*create()
{
struct node*p=&tree[top++];
p->data=0;
int i;
for(i=0;i<26;i++)
{
p->next[i]=NULL;
}
return p;
};
void insertt(char a[],struct node*root)
{
struct node*p=root;
int n,i;
n=strlen(a);
for(i=n-1;i>=0;i--)
{
int x=a[i]-'0';
if(p->next[x]==NULL)
p->next[x]=create();
p->data++;
p=p->next[x];
}
}
int searchh(char a[],struct node*root)
{
struct node*p=root;
int i,n,num;
num=0;
n=strlen(a);
for(i=n-1;i>=0;i--)
{
int x=a[i]-'0';
if(p->next[x]==NULL)
return 0;
p=p->next[x];
}
return p->data;
}
int main ()
{
int n,m;
char a[10];
while(scanf("%d",&n)!=EOF)
{
top=0;
struct node*root=create();
while(n--)
{
scanf("%s",a);
insertt(a,root);
}
scanf("%d",&m);
while(m--)
{
scanf("%s",a);
printf("%d\n",searchh(a,root));
}
}
return 0;
}
9万+

被折叠的 条评论
为什么被折叠?



