字典树:字符串的包含

题面:

给定一些仅有 01 组成的二进制编码串, 询问是否存在一个串是另一个串的前缀

多组数据输入。每组数据中包含多个仅有01组成的字符串,以一个9作为该组数据结束的标志。

对于第 k 组数据(从1开始标号),如果不存在一个字符串使另一个的前缀,输出"Set k is immediately decodable",否则输出"Set k is not immediately decodable"。

每组数据的输出单独一行

sample input:
01
10
0010
0000
9
01
10
010
0000
9

sample output:
Set 1 is immediately decodable
Set 2 is not immediately decodable

字典树:
  • 用于单个字符串与一堆字符串之间的匹配
  • 从根节点开始插入所有字符串,每一次遇到没有分配过的节点就创建新的节点并标记所有字符串末尾的节点,构建字典树
  • 插入函数示例:
    在这里插入图片描述
  • query函数用于查询是否存在某一个字符串是str的完整前缀,查询过程中flag==1,说明遇到了字符串的结尾,说明存在字符串是给定的字符串的完整前缀
思路:
  • 本题题意为一个字符串与一个字符串集合匹配,所以考虑使用字典树
  • 由于本题中只存在01两种字符,所以charset设置为2即可
  • 首先往字典树中一次插入每个字符串,假设当前字符串为S,需要判断两种情况:S是否是之前某个字符串的前缀,之前是否有某个字符串是S的前缀
  • 当S插入结束后,其最后一个节点是字典树中已经存在的节点,说明S为之前某个字符串的前缀
  • 在S的插入过程中,如果遇到某个字符串的结尾(判断flag),说明存在某个字符串是S的前缀
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
const int N=100001,charset=2;//字典树最多的节点个数,charset字符种类数 
struct tire
{
 int tot,root;//节点编号,root为根节点编号 
 int child[N][charset],flag[N];//flag[now]=1表示now是某一个字符串的结尾 
 tire()
 {
  memset(child,-1,sizeof(child));
  memset(flag,0,sizeof(flag));
  root=0;
  tot=0;
 }
 void clear()
 {
  memset(child,-1,sizeof(child));
  memset(flag,0,sizeof(flag));
  root=0;
  tot=0;
  } 
 int insert(char *str)
 {
  int now=root;
  int jud=0,len=strlen(str);
  for(int i=0;i<len;i++)
  {
   int temp=str[i]-'0';
   if(child[now][temp]==-1)//节点now没有第temp个儿子
   {
    child[now][temp]=++tot;
    flag[now]=0;
    } 
   else if(i==len-1||flag[child[now][temp]])//flag[child[now==1说明之前某个字符串是S的前缀 
    jud=1;
   now=child[now][temp];//i==len-1并且child[now !=-1说明给定的是之前某个字符串的前缀
   } 
  flag[now]=1;//标记该节点为字符的结尾
  return jud; 
 }
 bool query(char *str)
 {
  //查询字典树中是否存在某个完整的字符串是str的前缀
  int now=root;
  for(int i=0;i<strlen(str);i++)
  {
   int x=str[i]-'0';
   if(child[now][x]==-1)
    return false;//还没有找到尾就到头了
   if(flag[now]) return true;//已经找到了一个字符子串
   now=child[now][x]; 
   } 
  return false;//到头了还是没有找到一个子串 
 }
};
int main()
{
 tire t;
 string s;
 char c[1001];
 int count=0;
 bool fl=false;
 while(cin>>s)
 {
  if(s=="9")
  {
   count++;
   if(!fl)
    cout<<"Set "<<count<<" is immediately decodable"<<endl;
   else 
    cout<<"Set "<<count<<" is not immediately decodable"<<endl;
   t.clear();
   fl=false;
   continue;
  }
  strcpy(c,s.c_str());
  if(t.insert(c))
   fl=true;
 }
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值