hdoj 1004 Let the Balloon Rise
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.
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.
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
1 #include <iostream> 2 #include <bits/stdc++.h> //º¼µç²»ÈÏͬ 3 using namespace std; 4 typedef struct node{ 5 struct node*next[26]; 6 int value; 7 int num; 8 }*trie,node; 9 trie root; 10 11 void init_trie(trie&p){ 12 p=(trie)malloc(sizeof(node)); 13 for(int i=0;i<26;i++) 14 15 p->next[i]=0; 16 p->value=p->num=0; 17 } 18 void insert(trie p,char s[]) 19 { 20 int k=0; 21 while (s[k]!='\0') 22 { 23 if(!p->next[s[k]-'a']) 24 { 25 trie q; 26 init_trie(q); 27 p->next[s[k]-'a']=q; 28 } 29 p=p->next[s[k]-'a']; 30 p->num++; 31 k++; 32 } 33 p->value=1; 34 } 35 int find (trie p,char s[]){ 36 int k=0; 37 while(s[k]!='\0'&&p->next[s[k]-'a']) 38 { 39 40 p=p->next[s[k]-'a']; 41 k++; 42 } 43 if(s[k]=='\0') 44 return p->num; 45 return 0; 46 47 } 48 49 int main() 50 { int n; 51 while(scanf("%d",&n)!=EOF&&n) 52 { init_trie(root); 53 char ch[1005][17]; 54 for(int i=0;i<n;i++) 55 { 56 cin>>ch[i]; 57 insert(root,ch[i]); 58 } 59 int max=0,tem,f; 60 for(int i=0;i<n;i++) 61 { 62 tem=find(root,ch[i]); 63 if(tem>max) 64 { 65 max=tem; 66 f=i; 67 } 68 } 69 cout<<ch[f]<<"\n"; 70 71 } 72 return 0; 73 }