Immediate Decodability HDU - 1305(字典树模板题)

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.

Examples: Assume an alphabet that has symbols {A, B, C, D}

The following code is immediately decodable:
A:01 B:10 C:0010 D:0000

but this one is not:
A:01 B:10 C:010 D:0000 (Note that A is a prefix of C)

Input Write a program that accepts as input a series of groups of records from input. Each record in a group contains a collection of zeroes and ones representing a binary code for a different symbol. Each group is followed by a single separator record containing a single 9; the separator records are not part of the group. Each group is independent of other groups; the codes in one group are not related to codes in any other group (that is, each group is to be processed independently).
Output For each group, your program should determine whether the codes in that group are immediately decodable, and should print a single output line giving the group number and stating whether the group is, or 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
题意:给你一串01字符串,要你判断是否存在一串字符串是另一串的前缀,当输入的字符是“9”时结束输入,这道题数据比较水,请看下面的“正确”代码,代码只标记了以最后一个字符结尾的字符
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<set>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int N=1e5+1;
const int mod=1e9+7;
const double pi=acos(-1);
const double eps=1e-8;
char s[12];
int tot,trie[N][3];
bool flag,vis[N];//标记最后一个字符结尾的字符
void sert()
{
    int root=0;
    for(int i=0;s[i]!='\0';i++)
    {
        int id=s[i]-'0';
        if(!trie[root][id]) trie[root][id]=++tot;
        root=trie[root][id];
        if(vis[root]) flag=false;
    }
    if(vis[root]) flag=false;
    else vis[root]=true;
}
int main()
{
    int k=1;
    flag=true;
    while(gets(s))
    {
        if(s[0]=='9')
        {
            if(flag) printf("Set %d is immediately decodable\n",k++);
            else printf("Set %d is not immediately decodable\n",k++);
            flag=true,tot=0;
            memset(trie,0,sizeof(trie));
            memset(vis,false,sizeof(vis));
        }
        else sert();
    }
 }
/*
010
0000
01
9
*/这组数据应该输出 not 的

原因是什么呢,是因为 01 在 010 的后面出现的,当插入010的时候01这个前缀并没有出现所有就认定了这几串字符串中不存在前缀了。那么有什么办法可以解决呢?详情请看这篇文章 字典树


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页