秘密消息[trie树]

传送门

题意

给出a集合的0/1串,问b中的串 包涵a中的与被a中包涵的个数


把a中的建一个trie树,维护结尾的节点,路上经过的节点的cnt

查询b,就是到b路径中结尾的节点(包涵a) 和经过b结尾的节点(被包涵)


#include<bits/stdc++.h>
#define N 10005
#define M 500005
using namespace std;
int a[N],b[N],n,m;
int ch[M][2],cnt[M],rt[M],tot=1;
//b 包涵 a -> 顺着找rt 
//b 被 a 包涵  找b的端点的cnt 
void build(int x){
	int now=1;
	for(int i=1;i<=x;i++){
		int t; scanf("%d",&t); 
		if(!ch[now][t]) ch[now][t]=++tot;
		now=ch[now][t]; cnt[now]++; 
	}
	rt[now]++;
}
int find(int x){
	int now=1,ans=0;
	for(int i=1;i<=x;i++){
		int t; scanf("%d",&t); 
		now=ch[now][t];
		if(!now) continue;
		ans += rt[now]; 
	}
	ans += cnt[now]-rt[now];
	return ans;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++){
		int x; scanf("%d",&x);
		build(x);
	}
	for(int i=1;i<=m;i++){
		int x; scanf("%d",&x);
		printf("%d\n",find(x));
	}
}

猜你喜欢

转载自blog.csdn.net/sslz_fsy/article/details/83473044