字典树模板

▼魔方 西西 提交于 2019-11-26 10:30:01

字典树(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);


	}

``

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!