1. 程式人生 > 其它 >HDUOJ-----(1251)統計難題

HDUOJ-----(1251)統計難題

統計難題

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others) Total Submission(s): 14434    Accepted Submission(s): 6219

Problem Description

Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為字首的單詞數量(單詞本身也是自己的字首).

Input

輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串. 注意:本題只有一組測試資料,處理到檔案結束.

Output

對於每個提問,給出以該字串為字首的單詞的數量.

Sample Input

banana

band

bee

absolute

acm

ba

b

band

abc

Sample Output

2

3

1

0

Author

Ignatius.L

Recommend

Ignatius.L

     字典樹.....

程式碼:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 
 5 typedef struct trie
 6 {
 7     //由於只有小寫字母a~z-->26
 8     struct trie *child[26];
 9     int deep;  //--->相似的程度
10 }Trie;
11 
12 /*作為一個頭指標*/
13 
14 Trie *root;
15 
16 void Insert(char *a)
17 {
18     int len,i;
19     Trie *current, *creatnew;
20     len=strlen(a);
21     if(len)
22     {
23              current=root;
24         for(i=0;i<len;i++)
25         {
26           if(current->child[a[i]-'a']!=0)
27           {
28              current=current->child[a[i]-'a'];
29              current->deep=current->deep+1;
30           }
31           else
32           {
33               creatnew=(Trie *)malloc(sizeof(Trie));
34              for(int j=0;j<26;j++)
35              {
36                 creatnew->child[j]=0;
37              }
38               current->child[a[i]-'a']=creatnew;
39               current=creatnew;
40               current->deep=1;
41           }
42         }
43     }
44 }
45 
46 
47 int Triefind(char *a)
48 {
49    int i,len;
50    Trie *current;
51    len=strlen(a);
52    if(!len) return 0;
53    current=root;
54    for(i=0;i<len;i++)
55    {
56        if(current->child[a[i]-'a']!=0)
57        {
58          current=current->child[a[i]-'a'];
59        }
60        else
61             return 0;
62    }
63     return current->deep;
64 }
65 
66 int main()
67 {
68     int i;
69     char temp[12];
70     root=(Trie *)malloc(sizeof(Trie));
71     for(i=0;i<26;i++)
72     {
73         root->child[i]=0;
74     }
75     root->deep=2;
76     while(gets(temp),strcmp(temp,""))
77         Insert(temp);
78      memset(temp,'