统计难题

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

 

转载于:https://www.cnblogs.com/chujian123/p/3844157.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值