zoukankan      html  css  js  c++  java
  • HDU-1251-统计难题(字典树)

    链接:

    https://vjudge.net/problem/HDU-1251

    题意:

    Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

    思路:

    直接考虑字典数, 每个节点记录经过的次数,次数就是前缀数目.

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <vector>
    //#include <memory.h>
    #include <queue>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <math.h>
    #include <stack>
    #include <string>
    #include <assert.h>
    #include <iomanip>
    #define MINF 0x3f3f3f3f
    using namespace std;
    typedef long long LL;
    const int INF = 1e9;
    const int MAXN = 1e6+10;
    
    int cnt, n;
    char word[100];
    
    struct Node
    {
        int Ends;
        int Pass;
        int Next[30];
        void Init()
        {
            Ends = 0;
            Pass = 0;
            memset(Next, 0, sizeof(Next));
        }
    }Trie[MAXN];
    
    void Insert(char* val)
    {
        int root = 0;
        int len = strlen(val);
        for (int i = 0;i < len;i++)
        {
            if (Trie[root].Next[val[i]-'a'] == 0)
            {
                Trie[root].Next[val[i]-'a'] = ++cnt;
                Trie[cnt].Init();
            }
            root = Trie[root].Next[val[i]-'a'];
            Trie[root].Pass++;
        }
        Trie[root].Ends++;
    }
    
    int Query(char *val)
    {
        int root = 0;
        int len = strlen(val);
        for (int i = 0;i < len;i++)
        {
            if (Trie[root].Next[val[i]-'a'] == 0)
                return 0;
            root = Trie[root].Next[val[i]-'a'];
        }
        return Trie[root].Pass;
    }
    
    int main()
    {
        while (gets(word))
        {
            if (word[0] == '')
                break;
            Insert(word);
        }
        while (~scanf("%s", word))
        {
            printf("%d
    ", Query(word));
        }
    
        return 0;
    }
    
  • 相关阅读:
    JavaScript
    94.Binary Tree Inorder Traversal
    144.Binary Tree Preorder Traversal
    106.Construct Binary Tree from Inorder and Postorder Traversal
    105.Construct Binary Tree from Preorder and Inorder Traversal
    90.Subsets II
    78.Subsets
    83.Merge Sorted Array
    80.Remove Duplicates from Sorted Array II
    79.Word Search
  • 原文地址:https://www.cnblogs.com/YDDDD/p/11578092.html
Copyright © 2011-2022 走看看