zoukankan      html  css  js  c++  java
  • hdu 1251 统计难题(trie 树的简单应用)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

    题意:给你多个字符串,求以某个字符串为前缀的字符串数量。

    思路:简单的trie数应用,在trie的数据结构中增加一个存储到当前节点字符串出现的次数,在插入的过程中维护即可。

    code:

     1 #include <cstdio>
     2 #include <cstring>
     3 const int KIND = 26;
     4 struct TrieNode
     5 {
     6     int num;     // 遍历到该结点形成的字符串出现的次数
     7     TrieNode* next[KIND];
     8     TrieNode()
     9     {
    10         num = 1;
    11         for (int i = 0; i < KIND; ++i) next[i] = NULL;
    12     }
    13 };
    14 
    15 TrieNode* root = NULL;
    16 
    17 void Insert(char* x)
    18 {
    19     TrieNode* temp = root;
    20     if (root == NULL)   // 预判
    21     {
    22         temp = new TrieNode();
    23         root = temp;
    24     }
    25     int len = strlen(x);
    26     for (int i = 0; i < len; ++i)
    27     {
    28         int curr = x[i] - 'a';
    29         if (temp->next[curr] != NULL) ++(temp->next[curr]->num);  // 已经存在
    30         else temp->next[curr] = new TrieNode();  // 不存在
    31         temp = temp->next[curr];
    32     }
    33 }
    34 
    35 int Search(char* x)
    36 {
    37     int ret = 0;
    38     if (root == NULL) return ret;   // 预判
    39     TrieNode* temp = root;
    40     int len = strlen(x);
    41     for (int i = 0; i < len; ++i)
    42     {
    43         int curr = x[i] - 'a';
    44         if (temp->next[curr] == NULL) return 0;
    45         temp = temp->next[curr];
    46         ret = temp->num;
    47     }
    48     return ret;
    49 }
    50 
    51 void Release(TrieNode* root)
    52 {
    53     if (NULL == root) return;
    54     for (int i = 0; i < KIND; ++i)
    55     {
    56         if (root->next[i] != NULL)
    57             Release(root->next[i]);
    58     }
    59     delete root;
    60     root = NULL;
    61 }
    62 
    63 int main()
    64 {
    65     char str[10];
    66     while (gets(str))
    67     {
    68         if (str[0] == '')
    69         {
    70             while (gets(str))
    71                 printf("%d
    ", Search(str));
    72         }
    73         else Insert(str);
    74     }
    75     Release(root);
    76     return 0;
    77 }
  • 相关阅读:
    团队作业 总结
    个人作业 Alpha项目测试
    第二次作业
    交互式多媒体图书平台的设计与实现
    基于VS Code的C++语言的构建调试环境搭建指南
    码农的自我修养之必备技能 学习笔记
    工程化编程实战callback接口学习
    如何测评一个软件工程师的计算机网络知识水平和编程能力
    深入理解TCP协议及其源代码
    Socket与系统调用深度分析
  • 原文地址:https://www.cnblogs.com/ykzou/p/4483331.html
Copyright © 2011-2022 走看看