HDU 1004 Trie树

一道N久之前的题目了,等到今天才刷掉了:

http://acm.hdu.edu.cn/showproblem.php?pid=1004 

Let the Balloon Rise
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 37894 Accepted Submission(s): 13041


Problem Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges' favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.

This year, they decide to leave this lovely job to you.


Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) -- the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.

A test case with N = 0 terminates the input and this test case is not to be processed.


Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.


Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0


Sample Output
red
pink 

 

 AC code (用 Trie树.....)

#include <iostream>
#include <string.h>

using namespace std;

const int BranchNumber=26;

class TrieNode
{
public:
bool isStr;
int count; //记录单词的个数
TrieNode* next[BranchNumber];

TrieNode():isStr(false),count(0)
{
memset(next,NULL,sizeof(next));
}
};

class TrieTree
{
public :
TrieTree()
{
root=new TrieNode;
}
~TrieTree();

void Insert(const char* word);
int Search(const char* word);
void DeleteTrieTree(TrieNode* t);

private:
TrieNode* root;
};

TrieTree::~TrieTree()
{
DeleteTrieTree(root);
}

void TrieTree::Insert(const char* word)
{
if(root==NULL)
root=new TrieNode;

TrieNode* location=root;
while(*word)
{
if(location->next[*word-'a']==NULL)
location->next[*word-'a']=new TrieNode;
location=location->next[*word-'a'];
word++;
}
location->isStr=true;
location->count++;
}

int TrieTree::Search(const char* word)
{
if(root==NULL)
return 0;

TrieNode* location=root;
while(*word && location)
{
location=location->next[*word-'a'];
word++;
}

if(location!=NULL&& location->isStr)
return location->count;
else
return 0;
}

void TrieTree::DeleteTrieTree(TrieNode* t)
{
if(t!=NULL)
{
for(int i=0;i<BranchNumber;i++)
DeleteTrieTree(t->next[i]);
delete t;
t=NULL;
}
}

void Solution(int n)
{
int max,count;
char color[20];
char maxColor[20];

TrieTree trieTree;
max=0;

for(int i=0;i<n;i++)
{
cin>>color;
trieTree.Insert(color);
count=trieTree.Search(color);

if(count>max)
{
max=count;
strcpy(maxColor,color);
}
}
cout<<maxColor<<endl;
}

int main()
{
int n;
while(scanf("%d",&n) && n)
{
Solution(n);
}
return 0;
}


 

你可能感兴趣的:(trie)