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 }
  • 相关阅读:
    高仿IOS下拉刷新的粘虫效果
    CSDN无耻,亿赛通无耻
    2014年10月Android面试总结
    HttpClient和HttpURLConnection的使用和区别(下)
    HttpClient和HttpURLConnection的使用和区别(上)
    Gson简单使用
    Android PowerImageView实现,可以播放动画的强大ImageView
    Android访问网络,使用HttpURLConnection还是HttpClient?
    自定义android ProgressDialog
    NPOI导Excel样式设置
  • 原文地址:https://www.cnblogs.com/ykzou/p/4483331.html
Copyright © 2011-2022 走看看