24h購物| | PChome| 登入
2012-09-15 10:51:54| 人氣772| 回應0 | 上一篇 | 下一篇

[UVA][編碼檢查、Trie] 644 - Immediate Decodability

推薦 0 收藏 0 轉貼0 訂閱站台

  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 a data file. 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.


The Sample Input describes the examples above.

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

這個問題在離散數學中有講到過, 對於編碼必須只有唯一的一種解釋,
所以你必須將編碼方式建造成一棵字典樹(Trie), 然而對於某個編碼方式都會停留在葉節點,
如此一來才不會發生模稜兩可的轉譯情況


#include <stdio.h>
typedef struct {
int l, r, s;
} Node;
Node nd[10000];
int size, flag;
void Trie(char s[]) {
static int i, idx;
for(i = 0, idx = 0; s[i]; i++) {
if(s[i] == '0') {
if(!nd[idx].l)
++size, nd[idx].l = size,
nd[size].l = 0, nd[size].r = 0, nd[size].s = 0;
idx = nd[idx].l;
}
else {
if(!nd[idx].r)
++size, nd[idx].r = size,
nd[size].l = 0, nd[size].r = 0, nd[size].s = 0;
idx = nd[idx].r;
}
if(nd[idx].s) {
flag = 1;
return;
}
}
if(nd[idx].l || nd[idx].r)
flag = 1;
nd[idx].s = 1;
}
int main() {
char s[100];
int cases = 0;
while(gets(s)) {
flag = 0, size = 0;
nd[0].l = 0, nd[0].r = 0;
Trie(s);
while(gets(s)) {
if(s[0] == '9') break;
if(flag) continue;
Trie(s);
}
printf("Set %d is %simmediately decodable\n", ++cases, !flag ? "" : "not ");
}
return 0;
}
 

台長: Morris
人氣(772) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][摸擬] 397 - Equation Elation
此分類上一篇:[UVA][骰子翻轉比對] 253 - Cube painting

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文