HDU 1251 统计难题 (字符串-Trie树)

统计难题


Problem Description
Ignatius近期遇到一个难题,老师交给他非常多单词(仅仅有小写字母组成,不会有反复的单词出现),如今老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每一个提问都是一个字符串.

注意:本题仅仅有一组測试数据,处理到文件结束.
 

Output
对于每一个提问,给出以该字符串为前缀的单词的数量.
 

Sample Input
banana band bee absolute acm ba b band abc
 

Sample Output
2 3 1 0
 

Author
Ignatius.L
 

Recommend
Ignatius.L
 

题目大意:

给定一些单词,然后接下来非常多询问,每组一个字符串T。问你给定的单词中前缀为T的有多少个?

解题思路:

先依照给定的单词建一棵Trie树。记录值。然后每次查询就可以。

解题代码:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

const int maxn=500000;
int tree[maxn][30];
int val[maxn],cnt;


void insert(string st){
    int s=0;
    for(int i=0;i<st.length();i++){
        if( tree[s][st[i]-'a']==0 ) tree[s][st[i]-'a']=++cnt;
        s=tree[s][st[i]-'a'];
        val[s]++;
    }
}

int query(string st){
    int s=0;
    for(int i=0;i<st.length();i++){
        s=tree[s][st[i]-'a'];
        if(s==0) return 0;
    }
    return val[s];
}

int main(){
    string st;
    while( getline(cin,st) && st.length()>0 ){
        insert(st);
    }

    while(getline(cin,st)){
        cout<<query(st)<<endl;
    }
    return 0;
}




原文地址:https://www.cnblogs.com/mengfanrong/p/5185943.html