字典树(trie树)是一种根据字符串前缀在log(n)左右时间内完成查询的数据结构。
插入
这里可能需要节点数统计或者单词数统计
#include<bits/stdc++.h>
#include<tr1/unordered_map>
#define fi first
#define se second
#define show(a) cout<<a<<endl;
#define show2(a,b) cout<<a<<" "<<b<<endl;
#define show3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<P, int> LP;
const ll inf = 0x3f3f3f3f;
const int N = 1e6 + 10;
const ll mod = 10007;
const int base=131;
tr1::unordered_map<ll,ll> mp;
ll n,m,id,x,y,k,q;
ll num[N];//单词出现次数 或者 编号
ll tree[N][10];//tree[i][j]表示节点i的第j个儿子的节点编号
ll tot;//总结点数
void ins(char *str)//插入
{
int root=0;
for(int i=0;str[i];i++)
{
int id=str[i]-'0';
if(!tree[root][id]) tree[root][id]=++tot;
//num[tree[root][id]]++; //每个节点数统计
root=tree[root][id];
}
num[root]++;//单词数统计
}
void del(char *str)//删除
{
int root=0;
for(int i=0;str[i];i++)
{
int id=str[i]-'0';
//num[tree[root][id]]--; //每个节点数减少
root=tree[root][id];
}
num[root]--;//单词数减少
}
//查询
int query(char *str)
{
int root=0;
for(int i=0;str[i];i++)
{
int id=str[i]-'0';
if(!num[tree[root][id]])
{
return 0;
}
root=tree[root][id];
}
return num[root];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
``
来源:https://blog.csdn.net/weixin_42640692/article/details/98784790