现在的位置: 首页 > 综合 > 正文

hdu1004字典树

2014年10月30日 ⁄ 综合 ⁄ 共 609字 ⁄ 字号 评论关闭
#include <iostream>
#include <cstring>

using namespace std;

struct Trie
{
	int cnt;
	Trie* pNext[26];

	Trie()
	{
		cnt = 0;
		memset(pNext, NULL, sizeof(pNext));
	}
};

Trie* proot;

char ans[30];
int Max;

void Insert_Trie(char* s)
{
	Trie* p = proot;
	char* pa = s;

	while (*pa)
	{
		int j = *pa - 'a';
		if(p->pNext[j] == NULL)
			p->pNext[j] = new Trie;
		p = p->pNext[j];
		pa++;
	}
	p->cnt++;
	if (p->cnt > Max)
	{
		Max = p->cnt;
		strcpy(ans, s);
	}
	return ;
}



void Delete_Trie(Trie* p)
{
	for (int i = 0; i < 26; ++i)
	{
		if(p->pNext[i])
			Delete_Trie(p->pNext[i]);
	}
	delete p;
}

int main()
{
	int n;
	char str[30];
	while (cin>>n)
	{
		if(n == 0)
			break;
		Max = 0;
		proot = new Trie;
		while (n--)
		{
			cin>>str;
			Insert_Trie(str);
		}
		cout<<ans<<endl;
		Delete_Trie(proot);
	}
	return 0;
};

【上篇】
【下篇】

抱歉!评论已关闭.