• 【洛谷P2922】Secret Message


    题目大意:给定 N 个字符串组成的字典,有 M 个询问,每次给定一个字符串,求字典中有多少个单词为给定字符串的前缀或前缀是给定的字符串。

    题解:在 trie 上维护一个 tag 表示有多少字符串以当前字符串为前缀,ed 表示从该节点到根节点之间为一个字符串。
    对于给定的字符串,在 trie 中顺序查找,在匹配的过程中累加经过节点的 ed 标记,表示有多少字符串为给定字符串的前缀。若匹配成功,则答案累加 tag 标记并减去最后一个节点的 ed 标记,防止重复计算。若匹配失败,只需输出记录的 ed 之和即可。

    代码如下

    #include <bits/stdc++.h>
    using namespace std;
    const int maxn=5e5+10;
    
    int trie[maxn][2],tot=1,tag[maxn],ed[maxn];
    int m,n,len,s[10010];
    
    void insert(int *ss){
    	int now=1;
    	for(int i=1;i<=len;i++){
    		int ch=ss[i];
    		if(!trie[now][ch])trie[now][ch]=++tot;
    		now=trie[now][ch],++tag[now];
    	}
    	++ed[now];
    }
    void query(int *ss){
    	int now=1,ret=0;
    	for(int i=1;i<=len;i++){
    		int ch=ss[i];
    		if(!trie[now][ch]){
    			printf("%d
    ",ret);
    			return;
    		}
    		now=trie[now][ch];
    		ret+=ed[now];
    	}
    	printf("%d
    ",ret+tag[now]-ed[now]);
    }
    
    int main(){
    	scanf("%d%d",&m,&n);
    	for(int i=1;i<=m;i++){
    		scanf("%d",&len);
    		for(int j=1;j<=len;j++)scanf("%d",&s[j]);
    		insert(s);
    	}
    	for(int i=1;i<=n;i++){
    		scanf("%d",&len);
    		for(int j=1;j<=len;j++)scanf("%d",&s[j]);
    		query(s);
    	}
    	return 0;
    }
    
  • 相关阅读:
    pandas 筛选指定行或者列的数据
    数据相关性分析方法
    导入sklearn 报错,找不到相关模块
    特征探索经验
    python 中hive 取日期时间的方法
    云从科技 OCR任务 pixel-anchor 方法
    五种实现左中右自适应布局方法
    vscode vue 代码提示
    js Object.create 初探
    webpack 加载css 相对路径 ~
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10824463.html
Copyright © 2020-2023  润新知