Trie字符串统计(字典树查询字符串出现次数)

Trie字符串统计(字典树查询字符串出现次数)_第1张图片
在这里插入图片描述

思路:字典树

#include 
#include 
#include 
#include 
#include 
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXX 100005
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
//#include
using namespace std;
//const int MAX =100;
const double PI = 3.14159265359;
//const int mod = 1e9 + 7;
int n, m;
struct node
{
     
    int x, y;ll num;
    bool operator <(const node other)const
    {
     
        return num > other.num;

    }
};
int trie[400001][26], len, root, tot,sum[400001];
bool p;

void insert(string s)
{
     
    len = s.size();
    root = 0;
    for (int i = 0; i < len; i++)
    {
     
        int id = s[i] - 'a';
        if (!trie[root][id]) trie[root][id] = ++tot;
        root = trie[root][id];
    }
    sum[root]++;
}
int search(string s)
{
     
    root = 0;
    len = s.size();
    for (int i = 0; i < len; i++)
    {
     
        int id = s[i] - 'a';
        if (!trie[root][id])return 0;
        root = trie[root][id];
    }
    return sum[root];
}
int main()
{
     
   int t;
   cin>>t;
   while(t--)
   {
     

       string x,y;
       cin>>x>>y;
       if(x[0]=='I')
       {
     
           insert(y);
       }
       else
       {
     
           cout<<search(y)<<endl;;
       }
   }
    return 0;

}


你可能感兴趣的:(字典树)