日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

hdu 1251 统计难题(字典树)

發布時間:2025/1/21 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 hdu 1251 统计难题(字典树) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

分析:

關于字典樹的題目似乎都有一個普通適用性的模板,有時只是稍加改動來滿足臨時的要求,我的一個簡單的模板

#define MAXNUM 26 //定義字典樹結構體 typedef struct Trie {bool flag;//從根到此是否為一個單詞Trie *next[MAXNUM]; }Trie; //聲明一個根 Trie *root; //初始化該根 void init() {root = (Trie *)malloc(sizeof(Trie));root->flag=false;for(int i=0;i<MAXNUM;i++)root->next[i]=NULL; } //對該字典樹的插入單詞操作 void insert(char *word) {Trie *tem = root;while(*word!='\0'){if(tem->next[*word-'a']==NULL){Trie *cur = (Trie *)malloc(sizeof(Trie));for(int i=0;i<MAXNUM;i++)cur->next[i]=NULL;cur->flag=false;tem->next[*word-'a']=cur;}tem = tem->next[*word-'a'];word++;}tem->flag=true; } //查詢一個單詞的操作 bool search(char *word) {Trie *tem = root;for(int i=0;word[i]!='\0';i++){if(tem==NULL||tem->next[word[i]-'a']==NULL)return false;tem=tem->next[word[i]-'a'];}return tem->flag; }
//釋放字典樹內存操作,由于本題測試數據后程序自動跳出,所以這里沒寫釋放內存函數
void del(Trie *cur)
{
??? for(int i=0;i<MAXNUM;i++)
??? {
??????? if(cur->next[i]!=NULL)
??????? del(cur->next[i]);
??? }
??? free(cur);
}

這道題目是一道典型的字典樹題目(Trie),題目解法類似于 hdu 1247 Hat’s Words??? 的解法,這里搜索前綴,然后對后邊用一個遞歸搜索就可以求出有多少字符串是以此字符串為前綴,注意本身也是自己的前綴。

?

#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #define MAXNUM 26 using namespace std; //單詞 char words[50005][12]; //定義字典樹 typedef struct Trie {bool flag;//從根到此是否為一個單詞Trie *next[MAXNUM]; }Trie;Trie *root; int count_num;void init() {root = (Trie *)malloc(sizeof(Trie));root->flag=false;for(int i=0;i<MAXNUM;i++)root->next[i]=NULL; }void insert(char *word) {Trie *tem = root;while(*word!='\0'){if(tem->next[*word-'a']==NULL){Trie *cur = (Trie *)malloc(sizeof(Trie));for(int i=0;i<MAXNUM;i++)cur->next[i]=NULL;cur->flag=false;tem->next[*word-'a']=cur;}tem = tem->next[*word-'a'];word++;}tem->flag=true; }void dfs(Trie *cur) {if(cur->flag)count_num++;for(int i=0;i<MAXNUM;i++){if(cur->next[i]!=NULL)dfs(cur->next[i]);} }int search(char *word) {Trie *tem = root;count_num = 0;for(int i=0;word[i]!='\0';i++){if(tem==NULL||tem->next[word[i]-'a']==NULL)return 0;tem=tem->next[word[i]-'a'];}dfs(tem);return 1; }int main() {init();int t=0;char w[12];while(gets(w)){if(*w=='\0')break;insert(w);t++;}while(scanf("%s",w)!=EOF){search(w);printf("%d\n",count_num);}return 0; }

總結

以上是生活随笔為你收集整理的hdu 1251 统计难题(字典树)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。