• 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

     
     
     
  • 相关阅读:
    jsp 特殊标签
    poj 1753 Flip Game 高斯消元 异或方程组 求最值
    zoj 3155 Street Lamp 高斯消元 异或方程组 求方案数
    poj1222 EXTENDED LIGHTS OUT 高斯消元解异或方程组 模板
    zoj 3930 Dice Notation 模拟
    zoj 3157 Weapon 线段树求逆序对数
    hdu 1242 Rescue BFS+优先队列
    hdu 3466 Proud Merchants 贪心+01背包
    zoj 3689 Digging 贪心+01背包
    hdu 2602 Bone Collector 01背包模板
  • 原文地址:https://www.cnblogs.com/cchun/p/2520065.html
Copyright © 2020-2023  润新知