跳到正文

剪贴板

剪贴板 r1htv0ye

原文
剪贴板信息

剪贴板信息

收录
更新
C++
//字典树 P8306
#include<bits/stdc++.h>
using namespace std;
const int N = 3e6 + 5;
int t[N][65],cnt[N],tot;
//cnt[第几位] = 该位在 t 中对应的情况出现的次数
//t[第几位][该位的字符] = 下一位的下标
//每位记录的是当字符为...时,下一位的下标
char s[N];
int find(char c) {//转化char为int,方便存储
	if(c >= 'A' && c <= 'Z') {
		return c - 'A';
	}
	else if(c >= 'a' && c <= 'z') {
		return c - 'a' + 26;
	}
	else {
		return c - '0' + 52;
	}
}
int new_node() {//新建节点并覆盖原来的信息
	tot ++;
	memset(t[tot],0,sizeof t[tot]);
	cnt[tot] = 0;
	return tot;
}
void init() {//初始化
	tot = -1;
	new_node();
}
void insert(char s[]) {
	int n = strlen(s),p = 0;
	for(int i = 0;i < n;i ++) {
		int c = find(s[i]);//字符转化
		if(!t[p][c]) {//如果当前不存在该种情况,则新建一个节点
			t[p][c] = new_node();
		}
		p = t[p][c];//到下一位匹配
		cnt[p] ++;//记录当前情况出现的次数
	}
}
int query(char s[]) {
	int n = strlen(s),p = 0;
	for(int i = 0;i < n;i ++) {
		int c = find(s[i]);//字符转化
		if(!t[p][c]) {//如果不存在该种情况,则说明没有出现
			return 0;
		}
		p = t[p][c];//到下一位匹配
	}
	return cnt[p];//找到了则返回出现的次数
}
int main() {
	int t;
	scanf("%d",&t);
	while(t --) {
		init();
		int n,q;
		scanf("%d%d",&n,&q);
		for(int i = 1;i <= n;i ++) {
			scanf(" %s",&s);
			insert(s);
		}
		for(int i = 1;i <= q;i ++) {
			scanf(" %s",&s);
			printf("%d\n",query(s));
		}
	}
	return 0;
}