Trie(字典树)

一、基本概念:
   Trie(字典树)是一种用于实现字符串快速检索的多叉树结构。Tire的每个节点都拥有若干个字符指针,若在插入或检索字符串时扫描到一个字符c,就沿着当前节点的c字符指针,走向该指针指向的节点。
   初始化:
   一棵空Trie仅包含一个根节点,该点的字符指针均指向空。

   插入:
   当需要插入一个字符串S时,我们令一个指针p起初指向根节点。然后,依次扫描S中的每个字符c:
   (1)若P的c字符指针指向一个已经存在的节点Q,则令P=Q。
   (2)若P的c字符指针指向空,则新建一个节点Q,令P的c字符指针指向Q,然后令P=Q。
   当S中的字符扫描完毕时,在当前节点P上标记它是一个字符串的末尾。

   检索:
   当需要检索一个字符串S在Trie中是否存在时,我们令一个指针P起初指向根节点,然后依次扫描S中的每个字符c:
   (1)若P的c字符指针指向空,则说明S没有被插入过Trie,结束检索。
   (2)若P的c字符指针指向一个已经存在的节点Q,则令P=Q。
   当S中的字符扫描完毕时,若当前节点P被标记为一个字符串的末尾,则说明S在Trie中存在,否则说明S没有被插入过Trie。

int trie[maxn][26],tot=1;

void _insert(char *str)
{
    int len=strlen(str),p=1;
    
    for(int k=0;k<len;k++)
    {
        int ch=str[k]-'a';
        if(trie[p][ch]==0) trie[p][ch]=++tot;
        p=trie[p][ch];
    }
    _end[p]=true;
}

bool _search(char *str)
{
    int len=strlen(str),p=1;
    for(int k=0;k<len;k++)
    {
        p=trie[p][str[k]-'a'];
        if(p==0) return false;
    }
    return _end[p];
}

二、例题:
(一)、HDU----1251 统计难题:
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm

ba
b
band
abc
Sample Output
2
3
1
0

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<set>
using namespace std;
int a[1000008][26]={0};
int sum[1000008]={0};
char str[20];
int cnt=0;
void _insert(void)
{
    int k;
    int r=0;
    for(int i=0;str[i];i++)
    {
        k=str[i]-'a';
        if(!a[r][k]) a[r][k]=++cnt;
        sum[a[r][k]]++;
        r=a[r][k];
    }
    return ;
}

int _find(void)
{
    int r=0;
    int k;
    for(int i=0;str[i];i++)
    {
        k=str[i]-'a';
        if(!sum[a[r][k]]) return 0;
        r=a[r][k];
    }
    return sum[r];
}

int main(void)
{
    while(gets(str),strlen(str)!=0)
        _insert();


    while(scanf("%s",str)!=EOF)
        printf("%d\n",_find());

    return 0;

}

   
   
(二)AcWing 142:
给定N个字符串S1,S2…SN,接下来进行M次询问,每次询问给定一个字符串T,求S1~SN中有多少个字符串是T的前缀。

输入字符串的总长度不超过106,仅包含小写字母。

输入格式
第一行输入两个整数N,M。

接下来N行每行输入一个字符串Si。

接下来M行每行一个字符串T用以询问。

输出格式
对于每个询问,输出一个整数表示答案。

每个答案占一行。

输入样例:
3 2
ab
bc
abc
abc
efg
输出样例:
2
0

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
const int maxn=1000002;
int trie[maxn][26];
int num[maxn];
int tot=0;
char str[maxn];
char str1[maxn];
int n,m;
void _insert(void)
{
    int p=0;
    for(int i=0;str[i];i++)
    {
        int ch=str[i]-'a';
        if(!trie[p][ch]) trie[p][ch]=++tot;
        p=trie[p][ch];
    }
    num[p]++;
}

int _search(void)
{
    int p=0;
    int sum=0;
    for(int i=0;str1[i];i++)
    {
        int ch=str1[i]-'a';
        p=trie[p][ch];
        sum+=num[p];
        if(!p) return sum;
    }
    return sum;
}

int main(void)
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%s",str);
        _insert();
    }
    for(int i=1;i<=m;i++)
    {
        scanf("%s",str1);
        printf("%d\n",_search());
    }
    return 0;
}

   
   

(三)、POJ3764:
异或在字典树上的应用:
异或的运算性质 a xor a = 0
In an edge-weighted tree, the xor-length of a path p is defined as the xor sum of the weights of edges on p:

⊕ is the xor operator.

We say a path the xor-longest path if it has the largest xor-length. Given an edge-weighted tree with n nodes, can you find the xor-longest path?

Input
The input contains several test cases. The first line of each test case contains an integer n(1<=n<=100000), The following n-1 lines each contains three integers u(0 <= u < n),v(0 <= v < n),w(0 <= w < 2^31), which means there is an edge between node u and v of length w.

Output
For each test case output the xor-length of the xor-longest path.
Sample Input
4
0 1 3
1 2 4
1 3 6
Sample Output
7
Hint
The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<string>
using namespace std;
const int maxn=100005;
const int _max=100005*32;
int head[maxn],ver[maxn*2],edge[maxn*2],nt[maxn*2];
int trie[_max][2];
int d[maxn];
int n,tot;
int cnt;
bool ha[maxn];

void init(void)
{
    tot=0;
    cnt=0;
    memset(head,0,sizeof(head));
    memset(d,0,sizeof(d));
    memset(trie,0,sizeof(trie));
    memset(ha,0,sizeof(ha));
    return ;
}

void add(int x,int y,int z)
{
    ver[++tot]=y,edge[tot]=z;
    nt[tot]=head[x],head[x]=tot;
}

void _insert(int x)
{
    int p=0;
    for(int i=30;i>=0;i--)
    {
        int k=(x>>i)&1;
        if(!trie[p][k]) trie[p][k]=++cnt;
        p=trie[p][k];
    }
    return ;
}

int _search(int x)
{
    int sum=0;
    int p=0;
    for(int i=30;i>=0;i--)
    {
        int k=(x>>i)&1;
        if(!trie[p][!k]) p=trie[p][k];
        else
        {
            sum |= 1<<i;
            p= trie[p][!k];
        }

    }
    return sum;
}

void dfs(int x,int k)
{
    for(int i=head[x];i;i=nt[i])
    {
        int y=ver[i],z=edge[i];
        if(ha[y]) continue;
        ha[y]=true;
        d[y]=k^z;
        dfs(y,d[y]);
    }
    return ;
}

int main(void)
{
    while(scanf("%d",&n)!=EOF)
    {
        int x,y,z;
        init();
        for(int i=1;i<n;i++)
        {
            scanf("%d%d%d",&x,&y,&z);
            x++,y++;
            add(x,y,z);
            add(y,x,z);
        }
        dfs(1,0);
        int ans=0;
        for(int i=1;i<=n;i++)
        {
            ans=max(ans,_search(d[i]));
            _insert(d[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}

   

   
   
字典树还有一种动态建树的方法,内存利用效率较高,不过一般来说数组已经完全可以满足需求。
结构体 加 链表 加 动态申请内存。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值