标签:orm 判断 数据 bool string 表示 两种 树的定义 count
字典树又叫做前缀树,任意一个或多个字符串可以构建一棵字典树用于存储多个串的公共前缀

在用链表构造的字典树中每一个节点有着一个数据域来存放该点代表的字符和26个指针分别指向a(A)~z(Z)26个可能出现的子字符,在寻找某个字符串是否出现时,从根节点出发不断向下查找配对,如果到了最后一个字符都存在则表示该前缀存在

用二维数组tree[i][j]来标识一颗字典树,其中i为父节点,j为子节点,程序开始时父节点为root节点。tree[i][j]表示节点i第j个儿子的编号【这里我们规定root的编号为0】



const int SIZE=10; 
 struct Trie
 {
     int count;//前缀出现的次数
     struct Trie *next[SIZE];//孩子节点的数目 
     bool isEnd; //判断到这个位置是否是一个单词
     string name; 
     Trie()//构造函数 
     {
         count=0;
         memset(next,0,sizeof(next));
         isEnd=false;
     } 
 };  
 struct Trie *root=new Trie;//建立根节点
 void Insert(string s)
 {
     int len=s.length();
     int pos;
     struct Trie *u=root;
     for(int i=0;inext[pos]==NULL)//数字在边上,或者说是以位置的方式体现,不需要存储 
             u->next[pos]=new Trie;
         u=u->next[pos];
         u->count++;     
     }
     u->isEnd=true;//表明为一个单词的节点
     u->name=s;//同时存储单词 
 } 
 int Search(string s)
 {
     struct Trie *u=root;
     int len=s.length();
     for(int i=0;inext[pos]==NULL)
             return 0;
         else
             u=u->next[pos];
     }
     return u->count;
 }
 

const int maxn =2e6+5;//如果是64MB可以开到2e6+5,尽量开大
 int tree[maxn][30];//tree[i][j]表示节点i的第j个儿子的节点编号
 bool flagg[maxn];//表示以该节点结尾是一个单词
 int tot;//总节点数
 void insert_(char *str)
 {
    int  len=strlen(str);
    int root=0;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-‘0‘;
        if(!tree[root][id]) tree[root][id]=++tot;
        root=tree[root][id];
    }
    flagg[root]=true;
 }
 bool find_(char *str)//查询操作,按具体要求改动
 {
     int len=strlen(str);
     int root=0;
     for(int i=0;i<len;i++)
     {
         int id=str[i]-‘0‘;
         if(!tree[root][id]) return false;
         root=tree[root][id];
     }
     return true;
 }
 void init()//最后清空,节省时间
 {
     for(int i=0;i<=tot;i++)
     {
        flagg[i]=false;
        for(int j=0;j<10;j++)
            tree[i][j]=0;
     }
    tot=0;
 }
 
标签:orm 判断 数据 bool string 表示 两种 树的定义 count
原文地址:https://www.cnblogs.com/PokimonMaster/p/12188791.html