zoukankan      html  css  js  c++  java
  • Trie树

    pz:Trie树->字典树

    就是查字典用到的树!

    具体来说就是一颗26叉树,代表璎文26个字母,这样查询单词起来就变得10分的快速了.

    build函数,建立Trie树

    s(search)函数,查找该使用前缀的单词出现次数

     记录一下偶滴辞典

    http://acm.hdu.edu.cn/showproblem.php?pid=1251模版题

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    char str[20];
    int trie[1000005][26];
    int cnt[1000005];
    int tot;
    
    void build()
    {
    	int p=0;
    	int len=strlen(str);
    	for(int i=0;i<len;i++)
    	{
    		if(trie[p][str[i]-'a']==0) trie[p][str[i]-'a']=++tot;
    		p=trie[p][str[i]-'a'];
    		cnt[p]++;
    	}
    }
    
    int s()
    {
    	int p=0;
    	int len=strlen(str);
    	for(int i=0;i<len;i++)
    	{
    		if(trie[p][str[i]-'a']==0) return 0;
    		p=trie[p][str[i]-'a'];
    	}
    	return cnt[p];
    } 
    
    int main()
    {
    	ios::sync_with_stdio(false);
    	
    	while(gets(str) && str[0]!='')
    	{
    		build();
    	}
    	while(scanf("%s",str)!=EOF)
    	{
    		cout<<s()<<endl;
    	}
    	
    		
    	return 0;
    }
    

    前缀统计

    题目描述

    给定N个字符串S1,S2...SN,接下来进行M次询问,每次询问给定一个字符串T,求S1~SN中有多少个字符串是T的前缀。

    输入字符串的总长度不超过10^6,仅包含小写字母。

    输入格式

    第一行两个整数N,M;

    接下来N行每行一个字符串Si ;

    接下来M行每行一个字符串表示询问。

    输出格式

    对于每个询问,输出一个整数表示答案

    输入输出样例

    输入 #1
    3 2
    ab
    bc
    abc
    abc
    efg
    输出 #1
    2
    0

    pz:和模版反了过来,但是代码cbd
    修改如下:
    1. tot只记录Si尾部字母
    2. 询问出现次数 返回值累加
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    char str[1000005];
    int trie[1000005][26];
    int cnt[1000005];
    int tot,n,m;
    
    void build()
    {
    	int p=0;
    	int len=strlen(str);
    	for(int i=0;i<len;i++)
    	{
    		if(trie[p][str[i]-'a']==0) trie[p][str[i]-'a']=++tot;
    		p=trie[p][str[i]-'a'];
    	}
    	cnt[p]++;
    }
    
    int s()
    {
    	int p=0,ans=0;
    	int len=strlen(str);
    	for(int i=0;i<len;i++)
    	{
    		if(trie[p][str[i]-'a']==0) return ans;
    		p=trie[p][str[i]-'a'];
    		ans+=cnt[p];
    	}
    	return ans;
    } 
    
    int main()
    {
    	ios::sync_with_stdio(false);
    	
    	cin>>n>>m;
    	for(int i=1;i<=n;i++)
    	{
    		cin>>str; 
    		build();	
    	}
    	for(int j=1;j<=m;j++)
    	{
    		cin>>str;
    		cout<<s()<<endl;
    	}
    	
    		
    	return 0;
    }
    

      2020/3/28 20:39

     
  • 相关阅读:
    SJTU T4143 推箱子
    Markdown基本语法
    命令行的操作——cd
    C++ ------- 类和对象
    数据结构------栈和队列
    MySQL------ 子查询
    MySQL------ SQL99语法
    C++------内存分区模型
    第三章------数据链路层
    MySQL------ SQL92语法
  • 原文地址:https://www.cnblogs.com/huaruoji/p/12589208.html
Copyright © 2011-2022 走看看