码迷,mamicode.com
首页 > 其他好文 > 详细

(字典树)HDU - 1251 统计难题

时间:2016-09-15 01:01:44      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251


 

题意:先给定一些单词构成字典,然后再查一些在字典中以一些字母串为前缀的单词有几个。


 

分析:很基础很普通的字典树题目,但是用动态的字典树会超时,所以要用静态的字典树。


代码:

 1 #include <set>
 2 #include <map>
 3 #include <list>
 4 #include <cmath>
 5 #include <queue>
 6 #include <vector>
 7 #include <bitset>
 8 #include <string>
 9 #include <cctype>
10 #include <cstdio>
11 #include <cstring>
12 #include <cstdlib>
13 #include <iostream>
14 #include <algorithm>
15 
16 using namespace std;
17 
18 typedef long long ll;
19 typedef unsigned long long ull;
20 #define inf (0x3f3f3f3f)
21 #define lnf (0x3f3f3f3f3f3f3f3f)
22 #define eps 1e-8
23 int sgn(double a){return a < -eps ? -1 : a < eps ? 0 : 1;}
24 
25 //--------------------------
26 
27 struct  Trie_node {
28     int cnt;
29     int next[26];
30 }tree[400010];
31 int nxt;
32 
33 int  createTrieNode() {
34     memset(&tree[nxt], 0, sizeof(Trie_node));
35     return nxt++;
36 }
37 
38 void Trie_insert(string& word) {
39     int rt=0;
40     int len=word.length();
41     for(int i=0;i<len;i++){
42         int id = word[i] - a;
43         if(!tree[rt].next[id]){
44             tree[rt].next[id]=createTrieNode();
45         }
46         rt=tree[rt].next[id];
47         tree[rt].cnt++;
48     }
49 }
50 
51 int Trie_search(string& word) {
52     int rt=0;
53     int len=word.length();
54     for(int i=0;i<len;i++){
55         int id=word[i]-a;
56         if(!tree[rt].next[id])return 0;
57         rt=tree[rt].next[id];
58     }
59     return tree[rt].cnt;
60 }
61 
62 string word;
63 
64 void init(){
65 
66 }
67 
68 void solve() {
69     nxt=1;
70     memset(&tree[0],0,sizeof(Trie_node));
71     while(getline(cin,word)) {
72         if(word=="")break;
73         Trie_insert(word);
74     }
75     while(getline(cin,word)){
76         cout<<Trie_search(word)<<endl;
77     }
78 }
79 
80 int main() {
81 
82 #ifndef ONLINE_JUDGE
83     freopen("in.txt", "r", stdin);
84     //freopen("out.txt", "w", stdout);
85 #endif
86     iostream::sync_with_stdio(false);
87     init();
88     solve();
89     return 0;
90 }

 

(字典树)HDU - 1251 统计难题

标签:

原文地址:http://www.cnblogs.com/tak-fate/p/5873924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!