题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1305
Problem Description 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
字典树 入门 , 正常的建树加查找 ,最后要记得删除。 还有一个重点 就是new 因为 初始化在结构体中
代码:
#include <iostream> #include <bits/stdc++.h> using namespace std; struct node { int t; node *child[2]; //二进制代表 0,1状态 node() //结构体初始化 { t=0; for (int i=0 ;i<2; i++) { child[i]=NULL; } } }; node *root; int flag=0; void buildtree(char *a) //建立字典树,并查找 { node *p; node * newnode; int i; p = root; for (i=0; i<strlen(a); i++) { int m = a[i]-'0'; //cout<<p->child[m]<<endl; if (p->child[m]!=NULL) //如果树中存在改节点,查找是否结束 { p = p->child[m]; if (i==(strlen(a)-1)||p->t==1) { flag=1; break; } } else //否则将节点插入树 { newnode = new node; p->child[m] = newnode; p = newnode; } } p->t=1; } void ended(node *head) //删除字典树 { for (int i=0; i<2; i++) { if (head->child[i]!=NULL) ended(head->child[i]); } delete head; } int main() { int count1=1; char a[100]; root = new node; while (scanf("%s",a)!=EOF) { if (a[0]=='9') { if (flag==1) printf("Set %d is not immediately decodable\n",count1++); else printf("Set %d is immediately decodable\n",count1++); flag=0; ended(root); root = new node; continue; } else { buildtree(a); } } return 0; }