HDU 1004 (字典树||map)

来源:互联网 发布:ncbi数据库下载 编辑:程序博客网 时间:2024/05/16 10:07

B - Let the Balloon Rise
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status Practice HDU 1004

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

5greenredblueredred3pinkorangepink0
 

Sample Output

redpink
 

题意:找出出现次数最多的单词


题解:这一题实际上直接用map就可以过,但是还是给出字典树的做法。直接是模板题



#include<iostream>#include<cstring>#include<algorithm>#include<string>using namespace std;#define N 1000char s[N][20];struct trie{int value;trie *child[30];trie(){value=0;memset(child,NULL,sizeof(child));}}*root;void insert(char *s){trie *x=root;for(int i=0;s[i];i++){int pos=s[i]-'a';if(x->child[pos]==NULL)x->child[pos]=new trie;x=x->child[pos];}x->value++;}int find(char *s){trie *x=root;for(int i=0;s[i];i++){int pos=s[i]-'a';if(x->child[pos]==NULL)return 0;x=x->child[pos];}return x->value;}void deal(trie *x){if(x==NULL)return ;for(int i=0;i<26;i++){if(x->child[i]!=NULL){deal(x->child[i]);}}delete x;}int main(){#ifdef CDZSCfreopen("i.txt","r",stdin);#endifint n;while(~scanf("%d",&n)&&n){root=new trie;string pp;int ans=-0x3f3f3f3f;for(int i=0;i<n;i++){scanf("%s",s[i]);insert(s[i]);}for(int i=0;i<n;i++){if(ans<find(s[i])){ans=find(s[i]);pp=s[i];}}deal(root);printf("%s\n",pp.c_str());}return 0;}







0 0
原创粉丝点击