HDU 1305 Immediate Decodability(二叉树)

题意:

       给一系列的01串A{str[0], str[1], str[2], ...},判断是否存在str[i]是str[j]的前缀的情况。

解法:

       使用二叉树,按照顺序把每个串插入二叉树中,如果在插入的过程中发现经过的节点是叶子节点这说明存在前缀的情况。

 

AC代码如下:

/* Author: ACb0y Date: 2010年12月4日19:36:36 ProblemID: HDU 1305 Immediate Decodability Type: binary tree Result: 3280298 2010-12-04 19:34:29 Accepted 1305 0MS 352K 1920 B G++ ACb0y */ #include <iostream> #include <vector> #include <stdio.h> #include <string> using namespace std; //01binary tree node struct node { node * p_zero; node * p_one; }; node * root; node * get_node() { node * pnode = (node *)malloc(sizeof(node)); pnode->p_one = NULL; pnode->p_zero = NULL; return pnode; } void create_tree() { root = get_node(); } int insert_tree(string str) { int length = str.size(); node * p_new = NULL; node * cur = root; for (int i = 0; i < length; ++i) { if (str[i] == '0') { if (cur->p_zero == NULL) { p_new = get_node(); cur->p_zero = p_new; cur = cur->p_zero; } else if (cur->p_zero != NULL && (cur->p_zero->p_one != NULL || cur->p_zero->p_zero != NULL)){ cur = cur->p_zero; } else { //叶子节点 return 0; } } else { if (cur->p_one == NULL) { p_new = get_node(); cur->p_one = p_new; cur = cur->p_one; } else if (cur->p_one != NULL && (cur->p_one->p_one != NULL || cur->p_one->p_zero != NULL)){ cur = cur->p_one; } else { //叶子节点 return 0; } } } return 1; } //释放空间 void clear_tree(node * pnode) { if (pnode->p_one == NULL && pnode->p_zero == NULL) { free(pnode); } else { if (pnode->p_one != NULL) { clear_tree(pnode->p_one); } if (pnode->p_zero != NULL) { clear_tree(pnode->p_zero); } free(pnode); } } int main() { vector<string> v; string input; int flag; int cas = 1; #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif while (cin >> input) { if (input == "9") { flag = 1; create_tree(); int length = v.size(); for (int i = 0; i < length; ++i) { if (!insert_tree(v[i])) { flag = 0; break; } } v.clear(); clear_tree(root); if (flag) { printf("Set %d is immediately decodable/n",cas); } else { printf("Set %d is not immediately decodable/n", cas); } ++cas; } else { v.push_back(input); } } return 0; }

你可能感兴趣的:(HDU 1305 Immediate Decodability(二叉树))