zoukankan      html  css  js  c++  java
  • (字典树)HDU

    原题链接: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 }
  • 相关阅读:
    Codeforces Round #401 (Div. 2)【A,B,C,D】
    HDU2874【LCA(模板)】
    ZOJ2898【折半搜索】
    zoj2901【DP·二进制优化】
    萌新笔记之鸽巢原理及其应用
    codeforces 547B【单调栈】
    Codeforces631C【栈维护+瞎搞】
    每天一节组合数学
    HDU 1506【单调栈】
    HDU 3410【单调栈】
  • 原文地址:https://www.cnblogs.com/tak-fate/p/5873924.html
Copyright © 2011-2022 走看看