字典树

HDU 1251 字典树



#include <iostream>

using namespace std;



const int kind = 26;



struct TreeNode

{

	int count;

	TreeNode *next[kind];



	TreeNode()

	{

		count = 1;

		for(int i = 0; i < kind; i++)

			next[i] = NULL;

	}

};





void Insert(TreeNode *&root, const char *word)

{

	TreeNode *p = root;

	int i, branch;

	i = branch = 0;



	if(NULL == p)

	{

		p = new TreeNode;

		root = p;

	}



	while(word[i])

	{

		branch = word[i] - 'a';

		if(p->next[branch])

			p->next[branch]->count++;

		else

			p->next[branch] = new TreeNode;



		i++;

		p = p->next[branch];

	}

}





int Search(TreeNode *&root, char *word)

{

	TreeNode *p = root;



	if(!p)

		return 0;



	int i, branch, ans;

	i = branch = ans = 0;



	while(word[i])

	{

		branch = word[i] - 'a';

		if(NULL == p->next[branch])

			return 0;

		ans = p->next[branch]->count;

		i++;

		p = p->next[branch];

	}

	return ans;

}





int main()

{



	char word[10], ask[10];

	TreeNode *root = NULL;

	while(gets(word))

	{

		if(word[0] == '\0')

			break;

		Insert(root, word);

	}



	while(gets(ask))

		cout<<Search(root, ask)<<endl;



	return 0;

}

你可能感兴趣的:(字典树)