連結:http://acm.hdu.edu.cn/showproblem.php?pid=1251
題目的意思已經很明白了:統計出以某個字串為首碼的單詞數量(單詞本身也是自己的首碼).
我這就直接給字典樹基礎模板了,給了一些注釋,望各位能理解
#include <iostream>#include <cstring>using namespace std;typedef struct tree //建立節點{ int num; struct tree *br[26]; //每一層有26個字母}Node;Node *head;void Tree_Insert(char str[])//建樹{ Node *t,*s=head; int i,j; int len=strlen(str); for(i=0;i<len;i++) { int id=str[i]-'a'; if(s->br[id]==NULL) { t=new Node; //在這個字母下面在開闢新的結點 for(j=0;j<=25;j++)//初始化新結點 { t->br[j] = NULL; } t->num=0; s->br[id]=t; //標記這個結點連結的子樹指標 } s=s->br[id]; //s指向下一個結點 s->num ++; //經過這個點的次數 }}int Tree_Find(char str[]) //搜尋過程,從每位字母開始搜{ Node *s = head; int count; int len=strlen(str); for(int i=0;i<len;i++){ int Id=str[i]-'a'; if(s->br[Id]==NULL) { count=0; return count ; } else{ s=s->br[Id]; count=s->num; } } return count;}int main(){ int i; head=new Node; //頭結點 for(i=0;i<=25;i++)//26個結點,初始化 { head->br[i]=NULL; head->num=0; } char tem[15]; while(gets(tem),strcmp(tem,"")) { Tree_Insert(tem); //建樹 } while(gets(tem)){ cout<<Tree_Find(tem)<<endl; } return 0;}