「一本通 2.3 练习 1」Immediate Decodability( 字典树 )

题目描述

原题来自:ACM Pacific NW Region 1998

给出一些数字串,判断是否有一个数字串是另一个串的前缀。

输入格式

输入数据为多组数据,每组数据读到 9 时结束。

输出格式

对于每组数据,如果不存在一个数字串是另一个串的前缀,输出一行 Set t is immediately decodable ,否则输出一行 Set t is not immediately decodable ,其中 t 是这一组数据的组号。

样例

样例输入

01
10
0010
0000
9
01
10
010
0000
9

样例输出

Set 1 is immediately decodable
Set 2 is not immediately decodable

数据范围与提示

原文如下:

An encoding of a set of symbols is said to be immediately decodable if no code for one symbol is the prefix of a code for another symbol. We will assume for this problem that all codes are in binary, that no two codes within a set of codes are the same, that each code has at least one bit and no more than ten bits, and that each set has at least two codes and no more than eight.

数字串只包含 0,1, 记每个数字串长度为 l,则 1 <= l <= 10。每组数据至少有 2个数字串,至多有 8个数字串。

题意:

给几组字符串,判断每一组中是否存在某个字符串是另一个字符串的前缀,如果不存在,则输出Set t is immediately decodable ,存在输出Set t is not immediately decodable (t是这一组数据的组号)。

思路:

1.输入是多组输入,但每一组输入的结束标志是遇见9结束。输入是以多组输入的形式先输入第一个字符串,之后在while循环内判断输入,如果输入的为9,则continue,输入的不为9时,则继续输入字符串,当第二个while循环遇见9时,说明输入彻底结束,后面没有输入了;

2.输出要认真看清,存在时输出语句中有not,不存在时输出没有not;

3.inserts函数中实现插入以及查找前缀的操作,先在Trie树中查找,如果没有找到,则将字符串插入Trie树中,注意字符串结尾的标记不能丢。

代码:

#include<stdio.h>
#include<string.h>
char a[50];
int t;
int ch[50][50];//二维数组存储Trie树
int bo[50]; //若bo=1则表示从根到该点经过的边上字母组成的字符串是实际字符串集合中的元素
int inserts(char a[])//插入字符串+查询
{
    int l=strlen(a);
    int u=1;   //1为根节点
    int flag=0;
    for(int i=0; i<l; i++) //++i和i++都是可以的
    {
        int c=a[i]-'0';
        if(!ch[u][c]) //先查询,若没有找到,则插入字符串
            ch[u][c]=++t; //若不存在这条边则要新建一个节点与转移边
        else if(i==l-1)
            flag=1; //没有插入任何新的结点

        u=ch[u][c]; //找下一个位置的结点  t为总点数
        if(bo[u]) //经过某个有标记的结点
            flag=1;
    }
    bo[u]=1;  //在串的结尾处将bo赋值,表示它代表一个实际字符串集合中的元素
    return flag;
}
int main()
{
    int k=0;
    while(~scanf("%s",a))
    {
        int s=0;
        k++;
        t=1; //t=1表示新建一个空结点作为Trie树的根  不能放在第二个while循环内
        memset(ch,0,sizeof(ch));//初始化
        memset(bo,0,sizeof(bo));
        if(a[0]=='9')
            continue;
        if(inserts(a)) //输入的第一个字符串也要插入
            s=1;
        while(~scanf("%s",a))
        {
            if(a[0]=='9')
                break;
            if(inserts(a))
                s=1;
        }
        if(!s)
            printf("Set %d is immediately decodable\n",k);
        else
            printf("Set %d is not immediately decodable\n",k);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值