zoukankan      html  css  js  c++  java
  • HDU1251统计难题trie

    hash的一个变种.



    构造的树形如上图,不过有一点要记住,就是这道题中,,用next[id]这个指针来作为节点的地址。而通过next[id]->count来存放有这种前缀的单词的个数。。。

    代码:

    #include<iostream> 
    #include<cstring> 
    using namespace std; 
    typedef struct Trie 

        Trie* next[26]; 
        int count; 
    } xixi; 
    xixi root; 
    void maketrie(char* str)   //建立树形 

        xixi *p=&root,*q; 
        int len=strlen(str); 
     
        for(int i=0; i<len; i++) 
        { 
            int id=str[i]-'a'
            if(p->next[id]==NULL) 
            { 
                q=(xixi*)malloc(sizeof(xixi)); 
                for(int j=0; j<26; j++) 
                { 
                    q->next[j]=NULL; 
                } 
                q->count=1
                p->next[id]=q; 
                p=p->next[id]; 
            } 
            else 
            { 
                p->next[id]->count++; 
                p=p->next[id]; 
            } 
        } 

    void findcount(char* str)   //计算出现这种前缀的个数count 

        xixi *p=&root; 
        int len=strlen(str); 
        for(int i=0; i<len; i++) 
        { 
            int id=str[i]-'a'
            if(p->next[id]==NULL) 
            { 
                cout<<'0'<<endl; 
                return ; 
            } 
            else 
            { 
                p=p->next[id]; 
            } 
        } 
        cout<<p->count<<endl; 
        return ; 

    int main(void

        char str[20]; 
        while(gets(str),str[0]!='\0')//这里要注意,不能用‘\n’作为结束,这样就错误了。(哎,还犯这种错误) 
     
        { 
            maketrie(str); 
        } 
        while(gets(str)) 
        { 
            findcount(str); 
        } 
        return 0

     
     
     
  • 相关阅读:
    Python引入pandas报错ValueError: numpy.ufunc has the wrong size, try recompiling
    Oracle TNS无法解析ORA-12154报错
    python两个一维list列表合并
    SQL数据表加索引CREATE INDEX
    Python 格式化输出
    Python中三个双引号的作用
    2.认识素描
    如何快速学习Tableau Desktop
    1.怎样学习素描
    正点原子嵌入式Linux笔记3——Ubuntu软件安装
  • 原文地址:https://www.cnblogs.com/cchun/p/2520065.html
Copyright © 2011-2022 走看看