前缀 CS精英挑战营,trie树典型题
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
// ================= 代码实现开始 =================
const int M = 505, L = 1000005;
// c:trie树上的边,c[x][y]表示从节点x出发(x从1开始),字符为y的边(y范围是0到25)
// sz:sz[x]表示x节点的子树中终止节点的数量(子树包括x自身)sz为size缩写
// cnt:trie树上节点的数目
int c[L][26], sz[L], cnt;
// 将字符串s加入到trie树中
// s:所要插入的字符串
void add(char *s) {
int x=0;
for(; *s; ++s){
int y = *s - 'a'; //将字符范围变成0到25,e分别对应字符a到z
if(!c[x][y]) //若这个字符所对应的边不存在,则需要新建一个节点
c[x][y] = ++cnt;
x = c[x][y]; //接着沿着边往下走
// ++sz[x];//如果此处用了,那么dfs和下面那句也可以删去。
}
++sz[x]; //此时x是终止节点
}
// 用于计算sz数组
// x:当前节点
void dfs(int x) {
for( int y=0; y<26; ++y ){
int z = c[x][y];
if(z){
dfs(z); //递归下去
sz[x] += sz[z];//如何计算sz数组
}
}
}
// 用字符串s沿着trie树上走,找到相应的节点
// s:所给字符串
// 返回值:走到的节点
int walk(char *s) {
int x=0;
for(; *s; ++s){
int y = *s - 'a';
if(!c[x][y])
return 0;
x=c[x][y];//x应该如何变化
}
return x;
}
// ================= 代码实现结束 =================
char s[M];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (; n--;) {
scanf("%s", s);
add(s);
}
dfs(0);
sz[0] = 0;
for (; m--;) {
scanf("%s", s);
printf("%d\n", sz[walk(s)]);
}
return 0;
}
如果采用hash算法。
const int M = 505;
const int Base1 = 233;
const int mo1 = 998244353;
const int Base2 =31;
const int mo1 = 19260817;
multiset<pair<int,int>> Hash; //重复hash需要写multiset
void add(char *s){
int h=0;
for(;*s! = 0; ++s ){
int a = *s - 'a' +1;
h1 = ((long long)h1*Base1 +a)%mo1;
h2 = ((long long)h2*Base2 +a)%mo2;
Hash.insert(pair<int,int>(h1,h2));
}
}
int ask(char *s){
int h1=0,h2=0;
for()
}