题解 | 《算法竞赛进阶指南》前缀统计

【题目】

给定N个字符串 S 1 , S 2 … S N S_1,S_2 \dots S_N S1,S2SN,接下来进行M次询问,每次询问给定一个字符串T,求 S 1 ∼ S N S_1 \sim S_N S1SN中有多少个字符串是T的前缀。输入字符串的总长度不超过 1 0 6 10^6 106,仅包含小写字母。

【题解】

Trie的裸题,用C++11(clang++ 3.9)疯狂出现段错误,结果C++14(g++ 5.4)提交就A了,莫得找到原因在哪。这道题的Trie即使每种小写字符都有26种小写字符的可能,而26种小写字符又有26种小写字符的可能。这道题总共的可能性即是 M A N L E N × 26 MANLEN \times 26 MANLEN×26,也就是 1 e 6 × 26 1e6 \times 26 1e6×26种可能性,而给每个可能性赋予独一无二的标记。标记的赋予和查找都是依照字符串的顺序依次遍历下去,就像一颗树一样,即是字符树。这个数据结构的话,还是看代码懂得更快点,看代码吧。

时间复杂度: O ( S U M L E N ) O(SUMLEN) O(SUMLEN),字符串总长度和。

#include<iostream>
#include<cstring>
#include<sstream>
#include<string>
#include<cstdio>
#include<cctype>
#include<vector>
#include<queue>
#include<cmath>
#include<stack>
#include<list>
#include<set>
#include<map>
#include<algorithm>
#define fi first
#define se second
#define MP make_pair
#define P pair<int,int>
#define PLL pair<ll,ll>
#define lc (p<<1)  
#define rc (p<<1|1)
#define MID (tree[p].l+tree[p].r)>>1
#define Sca(x) scanf("%d",&x)
#define Sca2(x,y) scanf("%d%d",&x,&y)
#define Sca3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define Scl(x) scanf("%lld",&x)
#define Scl2(x,y) scanf("%lld%lld",&x,&y)
#define Scl3(x,y,z) scanf("%lld%lld%lld",&x,&y,&z)
#define Pri(x) printf("%d\n",x)
#define Prl(x) printf("%lld\n",x)
#define For(i,x,y) for(int i=x;i<=y;i++)
#define _For(i,x,y) for(int i=x;i>=y;i--)
#define FAST_IO std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define STOP system("pause")
#define ll long long
const int INF=0x3f3f3f3f;
const ll INFL=0x3f3f3f3f3f3f3f3f;
const double Pi = acos(-1.0);
using namespace std;
template <class T>void tomax(T&a,T b){ a=max(a,b); }  
template <class T>void tomin(T&a,T b){ a=min(a,b); }
const int N=1e6+5;
struct Node{
	int id,val;
}trie[N][27];
char str[N];
int tot = 0;
int insert(){
	int len=strlen(str);
	int id=0;
	for(int i=0;i<len;i++){
		int ch = str[i]-'a';
		if(!trie[id][ch].id) trie[id][ch].id=++tot;
		if(i==len-1) trie[id][ch].val++;
		id = trie[id][ch].id;
	}
}
int query(){
	int len=strlen(str),ans=0,id=0;
	for(int i=0;i<len;i++){
		int ch = str[i]-'a';
		if(!trie[id][ch].id) break;
		ans += trie[id][ch].val;
		id = trie[id][ch].id;
	}
	return ans;
}
int main(){
	int n,m; Sca2(n,m);
	For(i,1,n){
		scanf("%s",str);
		insert();
	}
	For(i,1,m){
		scanf("%s",str);
		Pri(query());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值