zoukankan      html  css  js  c++  java
  • hihocoder #1014 : Trie树

    题目大意:

      给你一个n个单词的字典,然后再给你m个前缀,询问在这个字典中,每次我找到的以该前缀的字符串的个数。

    解题思路:

      看着代码一步一步学会的,就是简单的trie的应用。

    代码:

    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cmath>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    const int root=0;
    int tot;
    struct node
    {
        int cnt;
        int next[26];
        void newnode()
        {
            cnt=0;
            for(int i=0;i<26;i++)
            {
                next[i]=-1;
            }
        }
    }t[1000005];
    void clear()
    {
        tot=0;
        t[root].newnode();
    }
    void insert(char *str)
    {
        int p=root;
        int len=strlen(str);
        for(int i=0;i<len;i++)
        {
            int id=str[i]-'a';
            if(t[p].next[id]==-1)
            {
                t[++tot].newnode();
                t[p].next[id]=tot;
            }
            p=t[p].next[id];
            t[p].cnt++;
        }
    }
    int query(char *str)
    {
        int p=root;
        int len=strlen(str);
        for(int i=0;i<len;i++)
        {
            int id=str[i]-'a';
            if(t[p].next[id]==-1)
            {
                return 0;
            }
            p=t[p].next[id];
        }
        return t[p].cnt;
    }
    int main()
    {
        int n,m;
        char s[15];
        clear();
        scanf("%d",&n);
        while(n--)
        {
            scanf("%s",s);
            insert(s);
        }
        scanf("%d",&m);
        while(m--)
        {
            scanf("%s",s);
            printf("%d
    ",query(s));
        }
        return 0;
    }
    

      

  • 相关阅读:
    php判断远程图片是否防盗链
    php获取远程图片url生成缩略图的方法
    qq zone g_tk
    zend studio aptana
    qq音乐接口
    function https_request
    Eclipse 汉化
    php 邮箱替换*
    获取顶级域名函数
    weixin oauth api 使用
  • 原文地址:https://www.cnblogs.com/wikioibai/p/4783302.html
Copyright © 2011-2022 走看看