TRIE树 习题-前缀

前缀 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()
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值