zoukankan      html  css  js  c++  java
  • 【Trie模板】HDU1251-统计难题

    【题意】

    n统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
    【思路】
    裸题,不过G++好像会超内存,C++就不会。
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstdlib>
     4 #include<cstring>
     5 #include<algorithm>
     6 using namespace std;
     7 struct Trie
     8 {
     9     int sum;
    10     Trie *next[26];
    11     Trie()
    12     {
    13         sum=0;
    14         for (int i=0;i<26;i++) next[i]=NULL;
    15     }
    16 };
    17 Trie *root=new Trie;
    18 char str[10];
    19 
    20 void insert()
    21 {
    22     int len=strlen(str);
    23     Trie *tmp=root;
    24     for (int i=0;i<len;i++)
    25     {
    26         if (tmp->next[str[i]-'a']==NULL)
    27         {
    28             Trie *newnode=new Trie;
    29             tmp->next[str[i]-'a']=newnode;
    30         }
    31         tmp=tmp->next[str[i]-'a'];
    32         tmp->sum++;
    33     }
    34 }
    35 
    36 int find()
    37 {
    38     int len=strlen(str);
    39     Trie *tmp=root;
    40     for (int i=0;i<len;i++)
    41     {
    42         if (tmp->next[str[i]-'a']==NULL) return 0;
    43         tmp=tmp->next[str[i]-'a'];
    44     }
    45     return tmp->sum;
    46 }
    47 
    48 void release(Trie *root)
    49 {
    50     for (int i=0;i<26;i++)
    51         if (root->next[i]!=NULL) release(root->next[i]);
    52     free(root);
    53 }
    54 
    55 int main()
    56 {
    57     while (gets(str),strcmp(str,"")!=0) insert();
    58     while (scanf("%s",str)!=EOF) cout<<find()<<endl;
    59     release(root);
    60     return 0;
    61 }
  • 相关阅读:
    模板
    洛谷
    Codeforces
    Codeforces
    Codeforces
    Codeforces
    洛谷
    洛谷
    洛谷
    NOIP 普及组 2016 海港
  • 原文地址:https://www.cnblogs.com/iiyiyi/p/5180108.html
Copyright © 2011-2022 走看看