HDU1251

字典樹 模板題

使用數組寫法

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 1000000 + 10;
int trie[maxn][27];
int pre_sum[maxn];///統計前綴次數
//int vis_word[maxn];///單詞是否出現過
int tot = 0;
void t_insert(char str[]){
    int root = 0;
    int id;
    for(int i = 0; str[i]; i++){
        id = str[i] - 'a';
        if(!trie[root][id])
            trie[root][id] = ++tot;
        root = trie[root][id];
        pre_sum[root]++;
    }
}
int t_find(char str[]){
    int root = 0;
    int id;
    for(int i = 0; str[i]; i++){
        id = str[i] - 'a';
        if(!trie[root][id]) return 0;///沒找到這個單詞或者前綴
        root = trie[root][id];
    }
    //return 1;
    //return vis_word[root];
    return pre_sum[root];

}
int main(){
    //memset(trie, 0, sizeof(trie));
    //memset(pre_sum, 0, sizeof(pre_sum));
    //memset(vis_word, 0, sizeof(vis_word));
    char str[100];
    while(gets(str) && strcmp(str, "") != 0){
            t_insert(str);
    }
    int ans;
    while(scanf("%s", str) != EOF)
    {
        ans = t_find(str);
        printf("%d\n", ans);
    }
    return 0;
}


發佈了69 篇原創文章 · 獲贊 58 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章