zoukankan      html  css  js  c++  java
  • (模板)hdoj1251(字典树模板题)

    题目链接:https://vjudge.net/problem/HDU-1251

    题意:给定一系列字符串之后,再给定一系列前缀,对每个前缀查询以该字符串为前缀的字符串个数。

    思路:

      今天开始学字典树,从入门题开始。用数组实现,count数组表示每个结点出现次数,trie[0]为根节点。插入和查询一个字符串的复杂度为O(len)。len为字符串的长度。

    AC code:

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    
    const int maxn=1e6+5;   //树的大小,尽量开大点
    int trie[maxn][30],num[maxn],cnt;
    char str[15];
    
    void insert(char *s){
        int len=strlen(s);
        int u=0;
        for(int i=0;i<len;++i){
            int t=s[i]-'a';
            if(!trie[u][t]){
                ++cnt;
                memset(trie[cnt],0,sizeof(trie[cnt]));
                trie[u][t]=cnt;
            }
            u=trie[u][t];
            ++num[u];
        }
    }
    
    int query(char *s){
        int len=strlen(s);
        int u=0;
        for(int i=0;i<len;++i){
            int t=s[i]-'a';
            if(!trie[u][t]) return 0;
            u=trie[u][t];
        }
        return num[u];
    }
    
    int main(){
        cnt=0;
        memset(trie[0],0,sizeof(trie[0]));
        memset(num,0,sizeof(num));
        while(gets(str),str[0]!='')
            insert(str);
        while(~scanf("%s",str))
            printf("%d
    ",query(str));
        return 0;
    }
  • 相关阅读:
    手机APP远程空气质量监测应用
    SPI
    2017-10-14
    常量声明
    ios- nil NULL 和 NSNull
    Xcode搭建真机调试环境 图文实例
    ios notification
    集合对象总结
    集合对象(NSSet,NSMutableSet,NSIndexSet)
    词典对象(NSDictionary和NSMutableDictionary)
  • 原文地址:https://www.cnblogs.com/FrankChen831X/p/11829364.html
Copyright © 2011-2022 走看看