所谓字典树,就是Trie树,很容易理解,为什么叫字典树,就想查字典一样,查一个英文单词,则从第一个字母开始查,然后第二个,第三个。。。直到遍历完整个单词。
它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。
如图,这图是在网上查找到的,可以很直观的理解字典树。
hdu 1251题直观的字典树模板题,可以给刚入门的蒟蒻们练手(同蒟蒻。。。 下面给出AC代码
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<stack>
#include<queue>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<set>
#define mem(a,b) memset(a,b,sizeof(a))
#define memmax(a) memset(a,0x3f,sizeof(a))
#define pfn printf("\n")
#define ll __int64
#define mod 1000000007
#define sf(a) scanf("%d",&a)
#define sf64(a) scanf("%I64d",&a)
#define sf2(a,b) scanf("%d%d",&a,&b)
#define sf3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define sf4(a,b,c,d) scanf("%d%d%d%d",&a,&b,&c,&d)
#define sff(a) scanf("%f",&a)
#define sfs(a) scanf("%s",a)
#define sfs2(a,b) scanf("%s%s",a,b)
#define sfs3(a,b,c) scanf("%s%s%s",a,b,c)
#define sfc(a) scanf("%c",&a)
#define str(a) strlen(a)
#define debug printf("***\n")
const double PI = acos(-1.0);
const double e = exp(1.0);
const int INF = 0x7fffffff;;
template<class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template<class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> inline T Min(T a, T b) { return a < b ? a : b; }
template<class T> inline T Max(T a, T b) { return a > b ? a : b; }
bool cmpbig(int a, int b){ return a>b; }
bool cmpsmall(int a, int b){ return a<b; }
using namespace std;
typedef struct trie
{
trie *next[26];
int v;
};
trie *root;
void buildtrie(char *a)
{
trie *p=root,*q;
for(int i=0;i<strlen(a);i++)
{
int id=a[i]-'a';
if(p->next[id]==NULL)
{
q=(trie *)malloc(sizeof(trie));
q->v=1;
for(int j=0;j<26;j++)
q->next[j]=NULL;
p->next[id]=q;
p=p->next[id];
}
else
{
p->next[id]->v++;
p=p->next[id];
}
}
}
int findtrie(char *a)
{
trie *p=root;
for(int i=0;i<strlen(a);i++)
{
int id=a[i]-'a';
p=p->next[id];
if(p==NULL)
return 0;
}
return p->v;
}
void deltrie(trie *t)
{
if(t==NULL)
return ;
for(int i=0;i<26;i++)
{
if(t->next[i]!=NULL)
deltrie(t->next[i]);
}
free(t);
return ;
}
int main()
{
//freopen("data.in","r",stdin);
char a[20],c,pos[20];
root=(trie *)malloc(sizeof(trie));
for(int i=0;i<26;i++)
root->next[i]=NULL;
while(gets(a)&&a[0]!='\0')
buildtrie(a);
while(~sfs(pos))
{
int num=findtrie(pos);
printf("%d\n",num);
}
/*for(int i=0;i<26;i++)
{
if(root->next[i]!=NULL)
printf("%d\n",root->next[i]->v);
}*/
deltrie(root);
return 0;
}
字典树要记得释放内存,不然有些题可能会直接爆内存。