• Trie思想及模板


    参考博文:https://www.acwing.com/solution/content/14695/
    课程链接:https://www.acwing.com/video/260/
    例题链接:https://www.acwing.com/problem/content/837/

    思想

    用于高效的存储和查找字符串集合的数据结构,用Trie树的字符串一般要么是小写字母要么都是大写字母,类型不会多,字符串的长度也不会太长
    root为空节点,图中五角星的意思是标记有以该字母结尾的字符串,代码表示是cnt数组,记录以该字母结尾的字符串的数量

    例题

    该题目中都为26个字母,所以可以开辟son[][26]数组,来映射26个字母,该数组表示的是子节点,用son[]某节点的所有子节点,son[]列映射为子节点的值,son[][]的值表示该节点是第几个加入的不重复的节点。cnt[]数组标识字符串的结束,idx用来确定节点是否存在

    代码

    #include 
    
    using namespace std;
    
    const int N = 100010;
    
    int son[N][26], cnt[N], idx;
    char str[N];
    
    void insert(char *str)
    {
        int p = 0;
        for (int i = 0; str[i]; i ++ )
        {
            int u = str[i] - 'a';
            if (!son[p][u]) son[p][u] = ++ idx;
            p = son[p][u];
        }
        cnt[p] ++ ;
    }
    
    int query(char *str)
    {
        int p = 0;
        for (int i = 0; str[i]; i ++ )
        {
            int u = str[i] - 'a';
            if (!son[p][u]) return 0;
            p = son[p][u];
        }
        return cnt[p];
    }
    
    int main()
    {
        int n;
        scanf("%d", &n);
        while (n -- )
        {
            // 此处设置成op[2],而不是char op,是因为char op用scanf("%c")会读入一些空格或回车
            // 而char op[2]用scanf("%s")会忽略空格和回车
            char op[2];
            scanf("%s%s", op, str);
            if (*op == 'I') insert(str);
            else printf("%d\n", query(str));
        }
    
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
  • 相关阅读:
    热烈祝贺|天栩(广东)有限公司受邀参加2022世界滋补产业生态大会
    MIT课程分布式系统学习02——RPC and threads
    input文本去除括号和标点符号回车
    【ffmpeg】YUV实践
    curl 工具的使用
    VScode快捷键(win + mac)
    类别不均衡,离群点以及分布改变
    安装mmcv及GPU版本的pytorch及torchvision
    SpringBoot实现支付宝沙箱
    Flutter快学快用23 架构原理:为什么 Flutter 性能更佳
  • 原文地址:https://blog.csdn.net/qq_46689648/article/details/126130695