ch1601 前缀统计(字典树)

概述:给定n个字符串,进行m次询问,每次询问给一个字符串t,问在n个字符串里有几个是字符串t的前缀.
思路:字典树,每个点记一下,以这个点结尾的字符串有几个,查询的时候,一边走,一遍加.
ch登不上去,所以还没交,试了几个自己写的样例都对,就先将代码放上来

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+10;
const int maxxn=1e6+10;
struct node{
	int end;
	int a[26];
}trie[maxxn];
int tot=1;
void insert(char *str){
	int len=strlen(str),p=1;
	for(int k=0;k<len;k++){
		int ch=str[k]-'a';
		if(trie[p].a[ch]==0)
			trie[p].a[ch]=++tot;
		p=trie[p].a[ch];
	}
	trie[p].end++;
}
int search(char *str){
	int len=strlen(str),p=1,res=0;
	for(int k=0;k<len;k++){
		p=trie[p].a[str[k]-'a'];
		res+=trie[p].end;
		if(p==0)	break;
	}
	return res;
}
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	char s[maxn];
	for(int i=0;i<n;i++){
		scanf("%s",s);
		insert(s);
	}
	for(int i=0;i<m;i++){
		scanf("%s",s);
		printf("%d\n",search(s));
	}
	return 0;
} 
发布了36 篇原创文章 · 获赞 11 · 访问量 660

猜你喜欢

转载自blog.csdn.net/weixin_43822647/article/details/102702318
今日推荐