644 - Immediate Decodability(AC)
该题有ANSI C写了一遍,通过使用二叉树的思想可以很好的解决这个问题,该题是用UVa系统测评的,发现如果用标准的C写代码的话,语法要求真的
很严格,提交了几次都是语法错误,单行注释都报错,最要紧的是连内建的bool类型都没有,所以我用int型代替,下面是AC的代码
#include <stdio.h> #define Nil -1 char left[50], right[50], tree_index[50]; char code[40]; int top = 0; int tree_root = -1; char* out_buff_is = "Set %d is immediately decodable\n"; char* out_buff_not = "Set %d is not immediately decodable\n"; int inset_tree(char* buff) { char *p = buff; int parent; int child = tree_root; int is_new_node = 1; for( ; *p ; ++p) { parent = child; if(!is_new_node && left[child] == Nil && right[child] == Nil && child != tree_root) return 0; switch(*p) { case '0': if(left[child] == Nil) { child = top++; left[parent] = child; right[child] = Nil; left[child] = Nil; code[child] = *p; is_new_node = 1; } else { child = left[child]; is_new_node = 0; } break; case '1': if(right[child] == Nil) { child = top++; right[parent] = child; right[child] = Nil; left[child] = Nil; code[child] = *p; is_new_node = 1; } else { child = right[child]; is_new_node = 0; } break; } } return is_new_node; } int main() { char buff[20]; int is_decodable; int num_case; is_decodable = 1; num_case = 1; tree_root = top++; left[tree_root] = Nil; right[tree_root] = Nil; code[tree_root] = '-'; while(gets(buff)){ if(buff[0] == '9') { if(is_decodable) printf(out_buff_is,num_case); else printf(out_buff_not,num_case); ++num_case; top = 1; left[tree_root] = Nil; right[tree_root] = Nil; is_decodable = 1; } else if(is_decodable == 0) continue; if(!inset_tree(buff)) { is_decodable = 0; } } return 0; }