trie树学习资料:http://www.acmerblog.com/trie-tree-template-3700.html
trie树第一题
题意:给定n个字符串,求出每个字符串之前有几个与他相同的字符串。
模板:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define M 10009
#define maxn 26
typedef struct Tire //对于字典树 每个节点都有26个儿子节点
{
int tcount; //表示该节点前缀出现的次数
Tire* next[maxn]; //该节点的后续节点数组,也就是这个节点的儿子节点们,下标表示的儿子所对应的字母。
}Tire;
Tire* create()
{
Tire* tmp = new Tire;
tmp->tcount = 1;//新节点初始化个数为1
for(int i = 0;i < maxn;i++)
{
tmp->next[i] = NULL;
}
return tmp;
}
void insert(Tire* root,char* ch)
{
Tire* tmp = root;
int len = strlen(ch);
for(int i = 0;i < len;i++)
{
int k = ch[i] - 'a';
if(tmp->next[k]) tmp->next[k]->tcount++;
else tmp->next[k] = create();
tmp = tmp->next[k];
}
}
int search(Tire * root,char* ch)
{
if(root == NULL) return 0;
Tire* tmp = root;
int len = strlen(ch);
for(int i = 0;i < len;i++)
{
int k = ch[i] - 'a';
if(tmp->next[k]) tmp = tmp->next[k];
else return 0;
}
return tmp->tcount;
}
int main()
{
char s[309];
int n;
while(scanf("%d",&n) == 1)
{
Tire* root = create();
for(int i = 0;i < n;i++)
{
scanf("%s",s);
printf("%d\n",search(root,s));
insert(root,s);
}
}
return 0;
}
这道题是要判断是否有一样的字符串,那么我们就可以修改一下这个count的意义,表示这个字符串出现的次数,那么在插入的时候就不要每次都++,只有在这个字符串结束的最后一个字符插入后,再在这个节点的count上+1.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define M 10009
#define maxn 26
typedef struct Tire
{
int tcount; //表示这个字符串出现的次数
Tire* next[maxn];
}Tire;
Tire* create()
{
Tire* tmp = new Tire;
tmp->tcount = 0;
for(int i = 0;i < maxn;i++)
{
tmp->next[i] = NULL;
}
return tmp;
}
void insert(Tire* root,char* ch)
{
Tire* tmp = proot;
int len = strlen(ch);
for(int i = 0;i < len;i++)
{
int k = ch[i] - 'a';
if(!tmp->next[k]) tmp->next[k] = create();
tmp = tmp->next[k];
}
tmp->tcount++; //在最后再增加这个字符串出现的次数
}
int search(Tire * root,char* ch)
{
if(root == NULL) return 0;
Tire* tmp = root;
int len = strlen(ch);
for(int i = 0;i < len;i++)
{
int k = ch[i] - 'a';
if(tmp->next[k]) tmp = tmp->next[k];
else return 0;
}
return tmp->tcount;
}
int main()
{
char s[309];
int n;
while(scanf("%d",&n) == 1)
{
Tire* root = create();
for(int i = 0;i < n;i++)
{
scanf("%s",s);
printf("%d\n",search(root,s));
insert(root,s);
}
}
return 0;
}