POJ-3630 Phone List 字典树

本文介绍了一种使用三叉字典树的数据结构,并通过实际编程案例对比了使用指针和数组模拟系统堆的性能差异。通过对POJ1056及3630题目的实践,展示了如何优化内存操作提高算法效率。

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

写了个三叉的字典树,找了个题测试了一下,POJ 1056过了,但是在3630题那就TLE,原因是用指针写的申请内存和回收内存太废时间了。用数组模拟了一下系统堆,果断过。


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<string>
using namespace std;
struct Node
{
	char ch;
	int count;
	int lson, rson, subtree;
}Node[1000010];
int flag, top;
typedef int Nodelink;
Nodelink create(char ch)
{
	Nodelink p = top++;
	Node[p].ch = ch;
	Node[p].lson = 0;
	Node[p].rson = 0;
	Node[p].subtree = 0;
	Node[p].count = 0;
	return p;
}
void insert(char str[], Nodelink root)
{
	int i;
	Nodelink p = root;
	for(i = 0; i < strlen(str); i++)
	{
		while(Node[p].ch != str[i])
		{
			if(str[i] < Node[p].ch)
			{
				if(!Node[p].lson)Node[p].lson = create(str[i]);
				p = Node[p].lson;
			}
			else 
			{
				if(!Node[p].rson)Node[p].rson = create(str[i]);
				p = Node[p].rson;
			}
		}
		if(Node[p].subtree == 0)Node[p].subtree = create('\0');
		p = Node[p].subtree;
		if(Node[p].count)flag = 0;
	}
	if(p < top-1)flag = 0;
	Node[p].count ++;
}
int main()
{
	char str[15];
	int st;
	scanf("%d", &st);
	while(st--)
	{
		int n;
		scanf("%d", &n);
		top = 1;
		create('\0');
		flag = 1;
		int i;
		for(i = 0; i < n; i++)
		{
			scanf("%s", str);
			if(flag)insert(str, 1);
		}
		if(flag)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值