統計難題 HDU - 1251 -字典樹-連結串列實現
阿新 • • 發佈:2018-12-22
-
統計難題
- HDU - 1251
- 題意:輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞
- ,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串
-
#include<iostream> #include<cstring> #include<stdio.h> using namespace std; #define maxn 26 char str[maxn]; struct node { int num; struct node*nxt[maxn]; node() { for(int i=0; i<26; i++) nxt[i]=NULL; num=0; } } root; void updata(char *word) { node *p=&root; for(int i=0; word[i]; i++) { if(p->nxt[word[i]-'a']==NULL) p->nxt[word[i]-'a']=new node ; p = p->nxt[word[i]-'a']; p->num++; } } int fond(char *word) { node *p=&root; for(int i=0; word[i]; i++) { if(p->nxt[word[i]-'a']==NULL) return 0; p=p->nxt[word[i]-'a']; } return p->num; } int main() { while(gets(str)) { if(strlen(str)==0||str==" ") break; updata(str); } while(scanf("%s",str)!=EOF) printf("%d\n",fond(str)); return 0; }