NYOJ 290 動物統計加強版(字典樹題)
阿新 • • 發佈:2018-12-16
動物統計加強版
時間限制:3000 ms | 記憶體限制:150000 KB
難度:4
輸入
第一行輸入動物名字的數量N(1<= N <= 4000000),接下來的N行輸入N個字串表示動物的名字(字串的長度不超過10,字串全為小寫字母,並且只有一組測試資料)。
輸出
輸出這些動物中最多的動物的名字與數量,並用空格隔開(資料保證最多的動物不會出現兩種以上)。
樣例輸入
10 boar pig sheep gazelle sheep sheep alpaca alpaca marmot mole
樣例輸出
sheep 3
描述
在美麗大興安嶺原始森林中存在數量繁多的物種,在勘察員帶來的各種動物資料中有未統計數量的原始動物的名單。科學家想判斷這片森林中哪種動物的數量最多,但是由於資料太過龐大,科學家終於忍受不了,想請聰明如你的ACMer來幫忙。
#include<cstdio> #include<cstring> #include<stdlib.h> #include<cmath> #include<algorithm> using namespace std; const int maxn=30; int ans; typedef struct trie { int v; trie *next[maxn]; }trie; trie *head; char temp[15]; /*void init() { head=new trie; head->v=100; }*/ void init() { head=(trie *)malloc(sizeof(trie)); for(int i=0;i<maxn;i++) { head->next[i]=NULL; } } void insert(char *str) { int len =strlen(str); trie *p=head,*q; for(int i=0;i<len;i++) { int id=str[i]-'a'; if(p->next[id]==NULL) { q=(trie *)malloc(sizeof(trie)); for(int i=0;i<maxn;i++) { q->next[i]=NULL; } q->v=0; p->next[id]=q; p=p->next[id]; } else { p=p->next[id]; } } p->v++; if(p->v>ans) { ans=p->v; strcpy(temp,str); } } int main() { int t; scanf("%d",&t); char str[13]; init(); ans=0; while(t--) { scanf("%s",str); insert(str); //printf("%d\n",head->v); } printf("%s %d\n",temp,ans); }