hdu 1251 统计难题(字典树)
生活随笔
收集整理的這篇文章主要介紹了
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 统计难题(字典树)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据中心监控管理系统设计(之一)
- 下一篇: ie9怎么开兼容模式