zoukankan      html  css  js  c++  java
  • HDU1251 字典树板子题

    题意:中文题,统计以某字符串作为前缀的字符串个数

    刚学字典树,理解起来十分简单,就是维护一个多叉树,这里用的是链表版本,后面就用的是数组版本了,个人更喜欢数组版本,这里的链表版本就因为

    莫名其妙的错误 C++能过而g++就会MLE 可能是两者管理内存的方式不一样吧

     1 #include<iostream>
     2 #include<cstring>
     3 #include<cstdio>
     4 using namespace std;
     5 const int maxn=26;
     6 struct Trie{
     7     Trie*next[maxn];
     8     int flag;
     9     Trie(){
    10         flag=1;
    11         memset(next,0,sizeof(next));
    12     }
    13 }*root;
    14 void insert(char*str){
    15     int len=strlen(str);
    16     Trie*p=root,*q;
    17     for(int i=0;i<len;i++){
    18         int id=str[i]-'a';
    19         if(p->next[id]==NULL){
    20             q=new Trie();
    21             p->next[id]=q;
    22             p=p->next[id];
    23         }
    24         else {
    25             p=p->next[id];
    26             (p->flag)++;
    27         }
    28     }
    29 
    30 }
    31 int query(char*str){
    32     int len=strlen(str);
    33     Trie*p=root;
    34     for(int i=0;i<len;i++){
    35         int id=str[i]-'a';
    36         p=p->next[id];
    37         if(p==NULL)return 0;
    38     }
    39     return p->flag;
    40 }
    41 void Free(Trie*T){
    42     if(T==NULL)return ;
    43     for(int i=0;i<maxn;i++){
    44         if(T->next[i])Free(T->next[i]);
    45     }
    46     delete(T);
    47 }
    48 
    49 int main(){
    50     char temp[15];
    51     root=new Trie();
    52     while(fgets(temp,15,stdin)&&temp[0]!='
    '){
    53              temp[strlen(temp)-1]='';
    54             // cout<<temp<<endl;    
    55            insert(temp);
    56     }
    57     while(~scanf("%s",temp)){
    58         printf("%d
    ",query(temp));
    59     }
    60     Free(root);
    61     return 0;
    62 }
  • 相关阅读:
    并发编程2(并发编程1已记录完毕,可去前面文章翻找)
    服务器启动django项目
    大四实习期间公司遇到的一些知识点
    列表推导式、生成器表达式
    brewhome基本使用
    python float的四舍五入
    爬取狮城bbs困扰了我一天的Python基础题
    python pip安装模块失败的原因
    stringutil stringutils
    echars的使用
  • 原文地址:https://www.cnblogs.com/ttttttttrx/p/10252549.html
Copyright © 2011-2022 走看看