zoukankan      html  css  js  c++  java
  • AcWing 142 前缀统计 (Trie)

    题目链接:https://www.acwing.com/problem/content/144/

    Trie板子题

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    #include<cmath>
    #include<stack>
    #include<queue>
    using namespace std;
    typedef long long ll;
    
    const int maxn = 1000010;
    
    int n, m, root = 0, cnt = 0;
    char s[maxn]; 
    
    struct Trie{
    	int son[26];
    	int cnt;
    }trie[maxn];
    
    void insert(char *str){
    	int len = strlen(str);
    	int pos = root;
    	for(int i=0;i<len;++i){
    		int c = s[i] - 'a';
    		if(!trie[pos].son[c]) trie[pos].son[c] = ++cnt;
    		pos = trie[pos].son[c];
    	}
    	++trie[pos].cnt;
    }
    
    int query(char *str){
    	int res = 0;
    	int len = strlen(str);
    	int pos = root;
    	for(int i=0;i<len;++i){
    		int c = s[i] - 'a';
    		if(!trie[pos].son[c]) return res;
    		pos = trie[pos].son[c];
    		res += trie[pos].cnt;
    	}
    	return res;
    }
    
    ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }
    
    int main(){
    	n = read(), m = read();
    	
    	for(int i=1;i<=n;++i){
    		scanf("%s", s);
    		insert(s);
    	}
    	
    	for(int i=1;i<=m;++i){
    		scanf("%s", s);
    		printf("%d
    ",query(s));
    	}
    	
    	return 0;
    }
    
  • 相关阅读:
    python flask学习笔记
    语音识别2 -- Listen,Attend,and Spell (LAS)
    语音识别 1--概述
    keras中seq2seq实现
    ResNet模型
    Bytes类型
    Python操作文件
    Pyhon基本数据类型
    ping
    find
  • 原文地址:https://www.cnblogs.com/tuchen/p/13944457.html
Copyright © 2011-2022 走看看