Week 15 B ZJM 与生日礼物

在ZJM的生日派对上,Q老师赠送了一份加密礼物,挑战ZJM解决一个二进制编码谜题。问题在于识别一组二进制串中是否存在一个串作为另一个串的前缀。通过构建字典树,算法巧妙地解决了这一难题,确保了数据的立即可解码性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ZJM 与生日礼物

ZJM 收到了 Q老师 送来的生日礼物,但是被 Q老师 加密了。只有 ZJM 能够回答对 Q老师 的问题,Q老师 才会把密码告诉 ZJM。

Q老师 给了 ZJM 一些仅有 01 组成的二进制编码串, 他问 ZJM:是否存在一个串是另一个串的前缀.

Input

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

Output

对于第 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

问题分析

一个字符串和一个字符串集合匹配,因此考虑使用字典树。
往字典树中依次插入每个字符串,假设当前字符串为S,有两种情况需要判断:
(1)S是否为之前某个字符串的前缀
当字符串S插入结束后,其最后一个节点是字典树中已经存在的节点,则说明S为之前某个字符串的前缀。
(2)之前是否有某个字符串是S的前缀
在字符串S插入过程中,如果遇到某一个字典树中的节点为某一个字符串的结尾,则说明存在某个字符串是S的前缀。

代码实现

#include<iostream>
#include<string.h>
using namespace std;

struct trie{
	static const int N = 1010, charset = 2;
	int tot, root, child[N][charset], flag[N];
	trie() {
		memset(child, -1, sizeof(child));
		root = tot = 0;
	}
	void clear() {
		memset(child, -1, sizeof(child));
		root = tot = 0;
	}
	
	int insert(char *str) {
		int now = root, jud = 0, len = strlen(str);
		for(int i=0; i<len; i++)
		{
			int x = str[i] - '0';
			if(child[now][x]==-1){
				child[now][x]= ++tot;
				flag[now] = 0;
			}
			else if(i == len-1 || flag[child[now][x]])
			    jud=1;
			
			now = child[now][x];
		}
		flag[now]=1;//标记为结尾 
		return jud;
	}
	
	bool query(char *str) {
		int now = root;
		for(int i=0; str[i]; 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()
{
	char a[100];
	trie tree;
	int k=1;
	int suc=1; 
	while(cin>>a)
	{
		if(a[0]!='9')
		{
			if(tree.insert(a) == 1) suc = 0;
		}
		else{
			if(suc==0)
			    cout<<"Set "<<k<<" is not immediately decodable"<<endl;
			else
			    cout<<"Set "<<k<<" is immediately decodable"<<endl;
			suc = 1;
			tree.clear();
			k++;
		}
	}
 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值