统计难题

hdu1251:http://acm.hdu.edu.cn/showproblem.php?pid=1251

题意:Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

题解:Trie模板题。在插入每个单词的时候统计前缀的个数即可。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<algorithm>
 5 #define maxn 1100000
 6 using namespace std;
 7 struct Nod {        //0为无效值
 8     int lnk[26], val;
 9     void init() {
10         memset(lnk, 0, sizeof(lnk));
11         val = 0;
12     }
13 };
14 const char BASE = 'a';
15 struct Trie {
16     Nod buf[maxn];
17     int len;
18     void init() {
19         buf[len=0].init();
20     }
21     void insert(char * str) {
22         int now = 0;
23         for(int i = 0; str[i]; i ++) {
24             int & nxt = buf[now].lnk[str[i]-BASE];
25             if(!nxt)buf[nxt=++len].init();
26              now = nxt;
27              buf[now].val++;
28         }
29     }
30     int search(char * str) {
31         int now = 0;
32         for(int i = 0; str[i]; i ++) {
33             int & nxt = buf[now].lnk[str[i]-BASE];
34             if(!nxt)    return 0;
35             now = nxt;
36         }
37         return buf[now].val;
38     }
39 } trie;
40 char str[100];
41  int main(){
42      int n,m;
43    // scanf("%d",&n);
44     trie.init();
45 
46     while(gets(str),strcmp(str,""))
47     {
48         trie.insert(str);     //先建立字典树
49     }
50     while(gets(str))
51     {
52         printf("%d\n", trie.search(str));
53     }
54 
55  }
View Code

 

posted on 2014-07-15 10:12  天依蓝  阅读(129)  评论(0编辑  收藏  举报

导航