zoukankan      html  css  js  c++  java
  • HDU 1251 统计难题(字典树模板题)

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

    题意:
    给出一些单词,然后有多次询问,每次输出以该单词为前缀的单词的数量。

    思路:

    字典树入门题。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 using namespace std;
     5 const int maxn = 1000005;
     6 
     7 int num = 0;
     8 
     9 struct Trie
    10 {
    11     int son[26];
    12     int cnt;  //前缀数量
    13     int ends; //单词数量,在本题中其实并没有用到
    14 }t[maxn];
    15 
    16 void init(int x)
    17 {
    18     t[x].ends = 0;
    19     t[x].cnt = 0;
    20     memset(t[x].son,0,sizeof(t[x].son));
    21 }
    22 
    23 void insert(char* s)
    24 {
    25     int u = 0, n = strlen(s);
    26     for(int i=0;i<n;i++)
    27     {
    28         int c = s[i]-'a';
    29         if(!t[u].son[c])
    30         {
    31             num++;
    32             init(num);
    33             t[u].son[c] = num;
    34         }
    35         u = t[u].son[c];
    36         t[u].cnt++;
    37     }
    38     t[u].ends++;
    39 }
    40 
    41 int query(char* s)
    42 {
    43     int u = 0, n = strlen(s);
    44     for(int i=0;i<n;i++)
    45     {
    46         int c = s[i]-'a';
    47         if(t[u].son[c] == 0)  return 0;
    48         u = t[u].son[c];
    49     }
    50     return t[u].cnt;
    51 }
    52 
    53 char s[15];
    54 
    55 int main()
    56 {
    57     while(gets(s) && strcmp(s,"")!=0)  insert(s);
    58     while(scanf("%s",s)!=EOF)  printf("%d
    ",query(s));
    59     return 0;
    60 }
  • 相关阅读:
    vue中router与route的区别
    网络编程-20200427
    JSP-20200428
    Servelet-1
    多线程-20200422-高级应用
    20200415_多线程——重点是应用场景
    2020-04-13注解和反射
    HIVE
    流的关联关系
    排序算法整理——坑+后期的数据结构部分
  • 原文地址:https://www.cnblogs.com/zyb993963526/p/7892150.html
Copyright © 2011-2022 走看看