AcWing 142 前缀统计 (Trie)

题目链接:https://www.acwing.com/problem/content/144/

Trie板子题

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 1000010;

int n, m, root = 0, cnt = 0;
char s[maxn]; 

struct Trie{
	int son[26];
	int cnt;
}trie[maxn];

void insert(char *str){
	int len = strlen(str);
	int pos = root;
	for(int i=0;i<len;++i){
		int c = s[i] - 'a';
		if(!trie[pos].son[c]) trie[pos].son[c] = ++cnt;
		pos = trie[pos].son[c];
	}
	++trie[pos].cnt;
}

int query(char *str){
	int res = 0;
	int len = strlen(str);
	int pos = root;
	for(int i=0;i<len;++i){
		int c = s[i] - 'a';
		if(!trie[pos].son[c]) return res;
		pos = trie[pos].son[c];
		res += trie[pos].cnt;
	}
	return res;
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	n = read(), m = read();
	
	for(int i=1;i<=n;++i){
		scanf("%s", s);
		insert(s);
	}
	
	for(int i=1;i<=m;++i){
		scanf("%s", s);
		printf("%d\n",query(s));
	}
	
	return 0;
}
posted @ 2020-11-08 15:20  Tartarus_li  阅读(93)  评论(0编辑  收藏  举报