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

    //题意:给你多个字符串为一组,然后空一行后输入询问的字符串,你要输出以该字符串为前缀的字符串数目。

    //思路:如果要一一匹配真的是,不知道什么时候去了...所以使用字典树。这里使用数组去模拟。

    #include <iostream>
    #include <stdio.h>
    using namespace std;
    
    int trie[1000010][26];    //数组形式定义字典树,值存储的是下一个字符的位置
    int num[1000010]={0};    //附加值,以某一字符串为前缀的单词的数量
    int pos = 1;
    
    
    void Insert(char *word){
        int i;
        int p =0;//指针位置(统计数组num的指针)
        for(int i=0;i<strlen(word);i++){
            int n = word[i] - 'a';
            if(trie[p][n]==0){//如果对应当前位置没有值
                trie[p][n] = pos++;
            }
            p = trie[p][n];//从trie树中得到指向下一个方向的位置
            num[p]++;//p结点位置加一
        }
    
    }
    int Find(char *word){
        int i;
        int p = 0;
        for(i  =0;i<strlen(word);i++){
            int n = word[i] - 'a';
            if(trie[p][n]==0){
                return 0;
            }
            p = trie[c][n];//如果没有出现这个前缀则输出为0
        }
        return num[p];
    }
    
    
    int main()
    {
        char word[11];
        while(gets(word)){
            if(!strlen(word))    //如果word的长度为0
                break;
            Insert(word);
        }
        while(gets(word))
            printf("%d
    ",Find(word));
        return 0;
    }
  • 相关阅读:
    c语言中的隐式函数声明(转)
    static关键字
    Eclipse中spring项目的XML文件的问题
    spring 中c3p0的优化配置
    Mysql通过SQL脚本复制表
    tomcat 设置内存
    删除无限循环的文件夹-删除递归文件夹
    使用cnpm代替npm
    数据库框架的log4j日志配置
    Win7删除远程连接历史记录
  • 原文地址:https://www.cnblogs.com/Tianwell/p/11342096.html
Copyright © 2011-2022 走看看