字典树 之 hdu 1800

本文介绍了一种使用字典树解决特定问题的方法,即从一组非负整数中找出最长递增序列组成的集合,最终目标是确定这些集合的数量。通过去除前导零并利用字典树的数据结构特性,有效地解决了问题。
//  [7/5/2014 Sjm]
/*
刚开始看到这道题,感觉不是用字典树解决的题,但看到这句知道可能用到字典树:
less than 30 digits (只好用字符串保存了)
 
解题关键:
给定一组非负整数,不断从中选取出当前可以选出的最长的递增序列,组成一个集合,直到所给的非负整数全部取完。
我们发现,集合的个数即所要求的答案。
但是,什么又决定集合的个数呢? 举几个例子,便会发现是所给非负整数中重复最多的那个数。。。(由集合也可以联想到)
故可以用字典树解决。。。
(注意把前导零去掉)
*/
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int MAX = 10;

struct Trie{
	int Tcount;
	Trie* next[MAX];
	Trie(){
		Tcount = 0;
		memset(next, NULL, sizeof(next));
	}
};

Trie* Root;

int CreTrie(char* str)
{
	int len = strlen(str);
	Trie* p = Root;
	for (int i = 0; i < len; i++) {
		int pos = str[i] - '0';
		if (!(p->next[pos])) {
			p->next[pos] = new Trie;
		}
		p = p->next[pos];
	}
	p->Tcount++;
	return (p->Tcount);
}

void DelTrie(Trie* T)
{
	for (int i = 0; i < MAX; i++) {
		if (T->next[i]) {
			DelTrie(T->next[i]);
		}
	}
	delete[] T;
}

int main()
{
	//freopen("input.txt", "r", stdin);
	int N;
	while (~scanf("%d", &N)) {
		char str[35];
		Root = new Trie;
		int ans = 0;
		while (N--){
			scanf("%s", str);
			int len = 0;
			int i = 0;
			while (str[i] == '0') {
				i++;
			}
			ans = max(ans, CreTrie(str+i));
		};
		printf("%d\n", ans);
		DelTrie(Root);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值