zoukankan      html  css  js  c++  java
  • 字典树模板

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<cstdlib>
     4 #include<vector>
     5 #include<map>
     6 #include<iostream>
     7 #include<algorithm>
     8 using namespace std;
     9 struct trie
    10 {
    11     int cont;
    12     trie *next[27];
    13     trie()
    14     {
    15         cont=0;
    16         memset(next,0,sizeof(next));
    17     }
    18 };
    19 trie *root;
    20 void init(char *v)
    21 {
    22     trie *p=root;
    23     for(int i=0; v[i]; i++)
    24     {
    25         int pet=v[i]-'a';
    26         if(p->next[pet]==NULL)
    27             p->next[pet]=new trie();
    28         p=p->next[pet];
    29         p->cont++;
    30     }
    31 }
    32 int finde(char *v)
    33 {
    34     trie *p=root;
    35     int i;
    36     for(i=0; v[i]; i++)
    37     {
    38         int tep=v[i]-'a';
    39         if(p->cont==1)
    40             break;
    41         p=p->next[tep];
    42     }
    43     return i;
    44 }
    45 void del(trie *p)
    46 {
    47     for(int i=0; i<26; i++)
    48     {
    49         if(p->next[i]!=NULL)
    50             del(p->next[i]);
    51     }
    52     free(p);
    53 }
    54 int main()
    55 {
    56     char ch[1005][25];
    57     char v[25];
    58     int i=0;
    59     root=new trie();//先为跟节点申请内存;
    60     while(gets(ch[i]),strcmp(ch[i],""))
    61     {
    62         init(ch[i]);
    63         //strcpy(ch[i],v);
    64         i++;
    65     }
    66     for(int j=0; j<=i; j++)
    67     {
    68         char v[25];
    69         int t=finde(ch[j]);
    70         //printf("%s %d
    ",ch[j],t);
    71         printf("%s ",ch[j]);
    72         for(int k=0; k<t; k++)
    73             printf("%c",ch[j][k]);
    74         printf("
    ");
    75     }
    76     return 0;
    77 }
    油!油!you@
  • 相关阅读:
    MySQL关键性能监控(QPS/TPS)
    Python小技巧
    Redis高可用演进(一)
    防范XSS攻击
    java引用知识
    ehcache同步原理
    ehcache监控
    SecureCRT使用技巧
    JUC整理笔记五之梳理Varhandle(下)
    JUC整理笔记四之梳理VarHandle(上)
  • 原文地址:https://www.cnblogs.com/zzuli2sjy/p/5095011.html
Copyright © 2011-2022 走看看