hdu 1305 Immediate Decodability

传送门

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串。然后问你这些串中是否有些串是别的串的前缀。

【分析】

显然字典树的简单运用啊。对于每个节点,如果是字符串结尾就标记为1,然后判断每个01串在树上路径的时候是否碰到了1,如果有的话那么显然答案为not,否则的话就是yes。

【代码】

#include <bits/stdc++.h>
using namespace std;
const int maxm = 1e6+10;
struct p
{
    p*a[2];
    bool flag;
    p()
    {
        a[0] = NULL;
        a[1] = NULL;
        flag = false;
    }
}num[maxm];
char que[10000];
int flag = 1;
int g_case;
bool pri = false;
void add()
{
    p*now = &num[0];
    int len = strlen(que);
    for(int i = 0;i<len;i++)
    {
        if(now->a[que[i]-'0']==NULL)
        {
            now->a[que[i]-'0'] = &num[flag++];
        }
        now = now->a[que[i]-'0'];
        if(now->flag)
            pri = true;
    }
    now->flag = true;
}
void del(p*a)
{
    a->flag = false;
    if(a->a[0]!=NULL)
    {
        del(a->a[0]);
        a->a[0] = NULL;
    }
    if(a->a[1]!=NULL)
    {
        del(a->a[1]);
        a->a[1] = NULL;
    }

}
void ans()
{
    printf("Set %d is ",g_case++);
    if(pri) printf("not ");
    puts("immediately decodable");
    del(&num[0]);
    flag = 1;
    pri = false;
}
int main()
{
//    freopen("in.txt","r",stdin);
    g_case = 1;
    while(scanf("%s",que)!=EOF)
    {
        if(que[0]=='9')
            ans();
        else
            add();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mengzhongsharen/article/details/79385507
今日推荐