zoukankan      html  css  js  c++  java
  • HDU-5687 Problem C (字典树)插入,查找,删除

     1 #include <iostream>
     2 #include <algorithm>
     3 #include <cstring>
     4 #include <string>
     5 #include <vector>
     6 
     7 using namespace std;
     8 typedef long long ll;
     9 
    10 const int maxn = 1300005;
    11 int pos = 1;
    12 
    13 int trie[maxn][26];
    14 int num[maxn];
    15 
    16 void insert(string str)
    17 {
    18     int p = 0;
    19     for (int i = 0; str[i]; i++)
    20     {
    21         int n = str[i] - 'a';
    22         if (!trie[p][n])
    23         {
    24             trie[p][n] = pos++;
    25         }
    26         p = trie[p][n];
    27         num[p]++;
    28     }
    29 }
    30 
    31 int Find(string str)
    32 {
    33     int p = 0;
    34     for (int i = 0; str[i]; i++)
    35     {    
    36         int n = str[i] - 'a';
    37         if (!trie[p][n])
    38             return 0;
    39         p = trie[p][n];
    40     }
    41     return num[p];
    42 }
    43 
    44 void Delete(string str)
    45 {
    46     int p = 0;
    47     for (int i = 0; str[i]; i++)
    48     {
    49         int n = str[i] - 'a';
    50         if (!trie[p][n]) return;
    51         p = trie[p][n];
    52     }
    53     int cnt = num[p];
    54     // 先跑一遍,看有没有这个string。
    55     p = 0;
    56     for (int i = 0; str[i]; i++)
    57     {
    58         int n = str[i] - 'a';
    59         p = trie[p][n];
    60         num[p] -= cnt;
    61     }
    62     for (int i = 0; i < 26; i++)
    63     {
    64         trie[p][i] = 0;
    65     }
    66 }
    67 
    68 int main()
    69 {
    70     int t;
    71     cin >> t;
    72     string c, s;
    73     while (t--)
    74     {
    75         cin >> c >> s;
    76         if (c == "insert") insert(s);
    77         else if (c == "search")
    78         {
    79             if (Find(s)) cout << "Yes" << endl;
    80             else cout << "No" << endl;
    81         }
    82         else Delete(s);
    83     }
    84     return 0;
    85 }
  • 相关阅读:
    「题解」:$Six$
    「题解」:$Smooth$
    AFO
    纪念——代码首次达到近50K(更新:78.8K 2019行)
    meet-in-the-middle 基础算法(优化dfs)
    莫队学习笔记
    树链剖分学习笔记
    常用数论模板
    图论模板
    高精度模板(结构体封装,重载运算符)
  • 原文地址:https://www.cnblogs.com/zny0222/p/13681190.html
Copyright © 2011-2022 走看看