[hiho#1014 : Trie树](trie,模板)

题目

题目分析:

trie模板题,稍微需要注意的是,我们这里不仅仅是对字符串结尾进行标记。因为是要统计以某个前缀的个数,因此我们经过一个结点,就给它标记+1,所以最后统计以此为前缀的个数,就是刚好前缀的最后一个字符的标记数。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+10;
int ch[maxn][26], tot; 
int val[maxn];    // 结尾标记   
char s[maxn];

void clear(){ //初始化 
	memset(ch, 0, sizeof(ch));
	memset(val, 0, sizeof(val));
	tot = 0;
}

void insert(){
	int len = strlen(s);
	int u = 0;   // root
	for(int i=0; i<len; i++){
		int c = s[i]-'a';
		if(!ch[u][c])  // 没有这个结点,新开辟 
			ch[u][c] = ++tot;
		u = ch[u][c];
		val[u]++;   // 经过就标记+1 
	}  
}

int find(){
	int len = strlen(s);
	int u = 0;
	int ans = 0; 
	for(int i=0; i<len; i++){
		int c = s[i]-'a';
		if(!ch[u][c])  // 找不到了 
			return 0; 
		else
			u = ch[u][c];
	}
	return val[u];
}

int main(){
	int n, m;
	scanf("%d", &n);
	clear();   //初始化 
	for(int i=1; i<=n; i++){
		scanf("%s", s);
		insert();   // 建立trie 
	}
	scanf("%d", &m);
	for(int i=1; i<=m; i++){
		scanf("%s", s);
		printf("%d\n", find());   // trie中查找前缀 
	}
	return 0;
}
posted @ 2020-06-08 10:13  gdgzliu  阅读(121)  评论(0)    收藏  举报