1. 程式人生 > >統計難題(字典樹)

統計難題(字典樹)

Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為字首的單詞數量(單詞本身也是自己的字首). 

Input

輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串. 

注意:本題只有一組測試資料,處理到檔案結束. 

Output

對於每個提問,給出以該字串為字首的單詞的數量. 

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0

 

#include<iostream>
#include<cmath>
#include<string.h>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;

struct Trie{
    int v;
    Trie *next[26];
};
Trie root;
void createTrie(char *str)//建立字典樹
{
    int len = strlen(str);
    Trie *p = &root,*q;
    for(int i = 0;i<len;i++)
    {
        int id = str[i] - 'a';
        if(p->next[id] == NULL)
        {
            q=(Trie *)malloc(sizeof(root));//申請一塊新記憶體
            q->v = 1;
            for(int j = 0;j<26;j++)
            q->next[j] = NULL;
            p->next[id] = q;
            p = p->next[id];
        }
        else{
            p->next[id]->v++;
            p = p->next[id];
        }
    }
}
int findTrie(char *str)//在字典樹中查詢
{
    int len = strlen(str);
    Trie *p = &root;
    for(int i = 0; i< len;i++)
    {
        int id = str[i] - 'a';
        p = p->next[id];
        if(p == NULL)
            return 0;
    }
    return p->v;
}
int main(){
    char str[15];
    for(int i = 0;i<26;i++)
    {
        root.next[i] = NULL;
    }
    while(gets(str)&&str[0]!='\0')
    {
        createTrie(str);
    }
    while(cin>>str)
    {
        int ans = findTrie(str);
        cout<<ans<<endl;
    }
    return 0;
}