hdu 1004 Let the Balloon Rise(字典树)

题目链接: 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): 90644    Accepted Submission(s): 34459


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
 
Author
WU, Jiazhi
 
题目大意:输出出现次数最多的字符串。
解题思路:每次建一条树就在结尾的时候标记一下次数,找到最大的最后输出对应的字符串就可以了。
 
详见代码。
 
#include 
#include 
#include 

using namespace std;

struct node
{
    node *next[26];
    int Count;
    node()
    {
        for (int i=0; i<26; i++)
            next[i]=NULL;
        Count=0;
    }
};

char cc[5000];
node *p,*root=new node();
void insert(char *s)
{
    p=root;
    for (int i=0; s[i]; i++)
    {
        int k=s[i]-'a';
        if (p->next[k]==NULL)
            p->next[k]=new node();
        p=p->next[k];
    }
    p->Count++;
}

int Search(char *s)
{
    p=root;
    for (int i=0; s[i]; i++)
    {
        int k=s[i]-'a';
        if (p->next[k]==NULL)
            return 0;
        p=p->next[k];
    }
    //cout<Count<<" "<<"3333333333"<Count;
}

int main()
{
    int t;
    char ch[1010];
    int Max;
    while (~scanf("%d",&t))
    {
        Max=0;
        if (t==0)
            break;
        while (t--)
        {
            scanf("%s",ch);
            //gets(ch);
            insert(ch);
            int ans=Search(ch);
            if (ans>Max)
            {
                Max=ans;
                strcpy(cc,ch);
            }
        }
        printf ("%s\n",cc);
    }
    return 0;
}

你可能感兴趣的:(ACM,图论——字典树)