HDU1671 Phone List(必须删除字典树,否则Memory Limit Exceeded)

本文探讨了在处理多组测试实例时,如何通过字典树实现高效内存管理,避免内存泄露,通过递归方法成功降低了内存占用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的字典树题 目,但是这题有多组测试实例,所以每次建立完的字典树都要删除掉,开始时没删,结果内存超了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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值