HDU 1251 统计难题 字典树

HDU 1251 字典树解题
本文介绍了解决HDU 1251问题的方法,该问题要求统计给定前缀在一系列单词中出现的次数。通过构建简单的字典树来高效地完成任务,并提供了完整的C++实现代码。

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

题意:

  给出你一些单词,然后在给出一些前缀,然后问你这些前缀是前面给的单词的前缀的有多少个。

 

坑爹:

  

 

 解法:

  简单字典树。

 

View Code
 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct Node
 5 {
 6     int a;
 7     struct Node *son[26];
 8     int flag;
 9 };
10 struct Node *root;
11 char str[26];
12 
13 void init(struct Node **newNode)
14 {
15     *newNode = (struct Node*)malloc(sizeof(struct Node));
16     int i;
17     for(i=0; i<26; i++)
18     {
19         (*newNode)->son[i] = NULL;
20     }
21     (*newNode)->a = 1;
22     (*newNode)->flag = 0;
23 
24 }
25 
26 void insert()
27 {
28     struct Node *currNode = root;
29     int len = strlen(str);
30 
31     int i;
32     for(i=0; i<len; i++)
33     {
34         if(currNode->son[str[i]-'a'] != NULL)
35         {
36             currNode = currNode->son[str[i]-'a'];
37             currNode->a = currNode->a + 1;
38         }
39         else
40         {
41             struct Node *newNode = NULL;
42             init(&newNode);
43             currNode->son[str[i]-'a'] = newNode;
44             currNode = newNode;
45         }
46     }
47     currNode->flag++;
48 }
49 
50 int find()
51 {
52     struct Node *currNode = root;
53     int len = strlen(str);
54     if(len == 0)
55     {
56         return 0;
57     }
58     int i;
59     for(i=0; i<len; i++)
60     {
61         if(currNode->son[str[i]-'a'] != NULL)
62         {
63             currNode = currNode->son[str[i]-'a'];
64         }
65         else
66         {
67             return 0;
68         }
69     }
70     return currNode->a;
71 }
72 
73 int main()
74 {
75     init(&root);
76     while(gets(str))
77     {
78         if(strcmp(str,"") == 0)
79         {
80             break;
81         }
82         insert();
83     }
84     while(gets(str))
85     {
86         cout<<find()<<endl;
87     }
88     return 0;
89 }

 

转载于:https://www.cnblogs.com/pcpcpc/archive/2012/11/03/2752773.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值