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

【题目】

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

【题解】

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 ,也就是 1 e 6 × 26 1e6 \times 26 种可能性,而给每个可能性赋予独一无二的标记。标记的赋予和查找都是依照字符串的顺序依次遍历下去,就像一颗树一样,即是字符树。这个数据结构的话,还是看代码懂得更快点,看代码吧。

时间复杂度: O ( S U M L E N ) 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());
	}
}
发布了39 篇原创文章 · 获赞 9 · 访问量 1959

猜你喜欢

转载自blog.csdn.net/qq_36296888/article/details/103057775