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

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

    思路分析:该问题要求求出以某个字符串为前缀的单词数目,通过使用字典树,在字典树中添加count记录通过该结点的单词数目即可;

    查找时找到前缀的最后一个单词的结点的count值即为所求;

    代码如下:

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    const int KIND = 26;
    const int MAX_N = 20;
    struct Node
    {
        Node *next[26];
        int count;
        Node ()
        {
            count = 0;
            memset(next, 0, sizeof(next));
        }
    };
    
    void InsertTrie(Node *root, char *str)
    {
        Node *p = root;
        int i = 0, k = 0;
    
        while (str[i])
        {
            k = str[i] - 'a';
            if (!p->next[k])
                p->next[k] = new Node();
            p = p->next[k];
            p->count++;
            ++i;
        }
    }
    
    int Find(Node *root, char *str)
    {
        int i = 0, k = 0;
        Node *p = root;
    
        while (str[i])
        {
            k = str[i] - 'a';
            if (!p->next[k])
                return 0;
            p = p->next[k];
            ++i;
        }
        return p->count;
    }
    
    int main()
    {
        int ans = 0;
        char str[MAX_N];
        Node *root = new Node();
    
        while (gets(str) && strcmp(str,"") != 0)
            InsertTrie(root, str);
        while (gets(str))
        {
            ans = Find(root, str);
            printf("%d
    ", ans);
        }
        return 0;
    }
  • 相关阅读:
    Codeforces Round #313 (Div. 1) A.Gerald's Hexagon
    COJN 0585 800604鸡蛋的硬度
    COJN 0584 800603吃糖果
    COJN 0583 800602分苹果
    COJN 0575 800601滑雪
    昨天的补记
    重构的代码
    写了一个复杂的sql语句
    一个想法
    安装了C
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4663051.html
Copyright © 2011-2022 走看看