統計難題
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 13884 Accepted Submission(s): 5971Problem DescriptionIgnatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為首碼的單詞數量(單詞本身也是自己的首碼).
Input輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串.
注意:本題只有一組測試資料,處理到檔案結束.
Output對於每個提問,給出以該字串為首碼的單詞的數量.
Sample Input
bananabandbeeabsoluteacmbabbandabc
Sample Output
2310
思路:字典樹。
代碼:
#include <iostream>#include <cstdlib>#include <cstdio>#include <cstring>#define MAX 26using namespace std;int n,m;char ss[1005];struct Trie //Trie結點聲明{ int isStr; //記錄該結點處有多少單詞經過 Trie *next[MAX]; //兒子分支};void insert(Trie *root,const char*s) //將單詞s插入到字典樹中{ if(root==NULL||*s=='\0') return; int i; Trie *p=root; while(*s!='\0') { if(p->next[*s-'a']==NULL) //如果不存在,則建立結點 { Trie *temp=(Trie *)malloc(sizeof(Trie)); for(i=0; i<MAX; i++) { temp->next[i]=NULL; } temp->isStr=1; p->next[*s-'a']=temp; p=p->next[*s-'a']; } else { p=p->next[*s-'a']; p->isStr++; } s++; }}int search(Trie *root,const char*s){ Trie *p=root; while(p!=NULL&&*s!='\0') { p=p->next[*s-'a']; s++; } if(p!=NULL) return p->isStr; return 0;}void del(Trie *root) //釋放整個字典樹占的堆區空間{ int i; for(i=0; i<MAX; i++) { if(root->next[i]!=NULL) { del(root->next[i]); } } free(root);}int main(){ int i; Trie *root= (Trie *)malloc(sizeof(Trie)); for(i=0; i<MAX; i++) { root->next[i]=NULL; } root->isStr=0; while(1) { gets(ss); if(strlen(ss)==0||ss[0]==' ') break ; insert(root,ss); } while(gets(ss)!=NULL) { printf("%d\n",search(root,ss)); } del(root); //釋放空間很重要 return 0;}/*allocallalloalalall*/