HDU 1251 统计难题(字典树)

本文介绍了一种使用字典树(Trie)解决字符串匹配问题的方法,具体实现为统计给定单词列表中以特定字符串作为前缀的单词数量。通过构建字典树并遍历目标字符串来查找匹配项,最终返回匹配的单词计数。

 

题目大意

 

给了很多单词,现在要统计以某个字符串为前缀的单词的数量

 

做法分析

 

直接建字典树,初始化出每个节点被覆盖的次数,然后对于每一个字符串,直接统计即可

 

参考代码

 

HDU 1251
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 struct Tire
 8 {
 9     struct Node
10     {
11         Node *next[26];
12         int cnt;
13         Node()
14         {
15             for(int i=0; i<26; i++) next[i]=NULL;
16             cnt=0;
17         }
18     };
19     Node *root;
20     Tire()
21     {
22         root=new Node();
23     }
24 
25     void Insert(char buff[])
26     {
27         Node *u=root;
28         for(int i=0; buff[i]; i++)
29         {
30             int v=buff[i]-'a';
31             if(u->next[v]==NULL) u->next[v]=new Node();
32             u=u->next[v];
33             u->cnt++;
34         }
35     }
36 
37     int Find(char buff[])
38     {
39         Node *u=root;
40         for(int i=0; buff[i]; i++)
41         {
42             int v=buff[i]-'a';
43             if(u->next[v]==NULL) return 0;
44             u=u->next[v];
45         }
46         return u->cnt;
47     }
48 
49     void Free(Node *u)
50     {
51         for(int i=0; i<26; i++)
52             if(u->next[i]!=NULL) Free(u->next[i]);
53         delete u;
54     }
55 } tree;
56 
57 char str[15];
58 
59 int main()
60 {
61     while(gets(str), strcmp(str, "")!=0) tree.Insert(str);
62     while(gets(str)) printf("%d\n", tree.Find(str));
63     tree.Free(tree.root);
64     return 0;
65 }

 

AC通道

 

HDU 1251 统计难题

 

 

 

转载于:https://www.cnblogs.com/zhj5chengfeng/archive/2013/04/15/3021697.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值