简单的字典树题 目,但是这题有多组测试实例,所以每次建立完的字典树都要删除掉,开始时没删,结果内存超了8MB左右
加了delete操作后内存占用从39MB降到了3320K
删除用的是递归,是参考Discuss里的方法,之前自己用非递归写的,很麻烦,效果也不好,在此谢过分享代码的同学
下面是AC的代码:
// hdu1671
#include <stdio.h>
#include <string.h>
struct node{
bool is_over;
node * child[10];
int child_num;
node(){
is_over = false;
child_num = 0;
memset(child, 0, sizeof(child));
}
};
bool add(char * str, node * next)
{
bool mark = false;
while(*str)
{
if(next->child[*str-'0'] == NULL)
{
next->child[*str-'0'] = new node();
next->child_num++;
mark = true;
}
next = next->child[*str-'0'];
if(next->is_over)
return false;
str++;
}
next->is_over = true;
if(mark == false)
return false;
return true;
}
void delete_tree(node * root)
{
//递归删除
for(int i=0; i<10; i++)
if(root->child[i] != NULL)
delete_tree(root->child[i]);
delete root;
}
int main(void)
{
//freopen("E:\\input.txt", "r", stdin);
int n;
char str[13];
scanf("%d", &n);
while(scanf("%d", &n) != EOF)
{
node * root = new node();
int i;
for(i=0; i<n; i++)
{
scanf("%s", str);
if(add(str, root) == false)
{
puts("NO");
break;
}
}
if(i < n-1)
{
i = n-1-i;
while(i--) scanf("%s", str);
}
else if(i == n)
puts("YES");
delete_tree(root);
}
return 0;
}