字典树

字典树能够用来查询某单词的前缀在所有单词中出现的次数,有查询和插入两个操作,查询和插入的时间复杂度都是O(n),是一种以空间换时间的方法

LA3942字典树的应用;

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib> 
#include<climits>
#include<cctype>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<string>
#define ll long long
#define MAX 300010
#define INF INT_MAX
#define eps 1e-8
#define MOD  20071027

using namespace std;

char s[MAX],t[MAX];
int ch[MAX][30],mark[MAX],dp[MAX],cnt;

void insert(){                                 //插入字符串 
	int n = strlen(t);
	int u = 0;
	for (int i=0; i<n; i++){
		int c = t[i] - 'a';
		if (!ch[u][c]){                         //建一个新节点 
			memset(ch[++cnt],0,sizeof(ch[cnt]));
			ch[u][c] = cnt;
		}
		u = ch[u][c];
	}
	mark[u] = n;                          //mark[]记录节点附加信息,此处当遇到字符串结尾时记录字符串长度。 
}

void query(char* st, int l){             //查询操作 
	int n = strlen(st);
	int u = 0;
	for (int i=0; i<n; i++){
		int c = st[i] - 'a';
		if (ch[u][c]){
			u = ch[u][c];
			if (mark[u]) dp[l] = (dp[l] + dp[l+mark[u]]) % MOD;   //如果mark[]不为0,则该节点为一个字符串的结尾节点 
		}
		else break;
	}
}

int main(){
	int m,T = 0;
	while(scanf("%s",s) != EOF){
		T++;
		memset(dp,0,sizeof(dp));
		memset(mark,0,sizeof(mark));
		memset(ch,0,sizeof(ch));
		cnt = 0;
		scanf("%d",&m);
		for (int i=0; i<m; i++){
			scanf("%s",t);
			insert();
		}
		int n = strlen(s);
		dp[n] = 1;
		for (int i=n-1; i>=0; i--){
			query(s+i,i);
		}
		printf("Case %d: %d\n",T,dp[0] % MOD);
	}
	return 0;
}



 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值