Trie树(1)模板+例题

模板

struct trie{
	int nex[maxn][26],idx;
	bool exist[maxn]; // 该结点结尾的字符串是否存在
	void insert(string s,int l){ // 插入字符串
		int p=0;
		for(int i=0;i<l;i++){
			int c=s[i]-'a';
			if(!nex[p][c]) nex[p][c]=++cnt;// 如果没有,就添加结点
			p=nex[p][c];
		}
		exist[p]=1;
	}
	bool find(string s,int l){// 查找字符串
		int p=0;
		for(int i=0;i<l;i++){
			int c=s[i]-'a';
			if(!nex[p][c]) return 0;
			p=nex[p][c];
		}
		return exist[p];
	}
};

应用1 检索字符串

link

思路:

在trie的基础上增加exist数组表示该单词出现了几次。

代码:

const int maxn=5e5+100;


	int nex[maxn][26],cnt=0;
	int exist[maxn]; // 该结点结尾的字符串是否存在
	void insert(string s,int l){ // 插入字符串
		int p=0;
		for(int i=0;i<l;i++){
			int c=s[i]-'a';
			if(!nex[p][c]) nex[p][c]=++cnt;// 如果没有,就添加结点
			p=nex[p][c];
		}
	}
	int find(string s,int l){// 查找字符串
		int p=0;
		for(int i=0;i<l;i++){
			int c=s[i]-'a';
			if(!nex[p][c]) return 0;
			p=nex[p][c];
		}
		exist[p]++;
		return exist[p];
	}

int main(){
	
	int n=read;
	while(n--){
		string s;cin>>s;
		insert(s,s.size());
	}
	int m=read;
	while(m--){
		string s;cin>>s;
		int t=find(s,s.size());
		if(t==0) puts("WRONG");
		else if(t==1) puts("OK");
		else puts("REPEAT");
	}
	
	
	
	
	
	return 0;
}
原文地址:https://www.cnblogs.com/OvOq/p/15028720.html