NYOJ 動物統計加強版(字典樹經典例子)

動物統計加強版

時間限制:3000 ms  |  內存限制:150000 KB
難度:4
描述
在美麗大興安嶺原始森林中存在數量繁多的物種,在勘察員帶來的各種動物資料中有未統計數量的原始動物的名單。科學家想判斷這片森林中哪種動物的數量最多,但是由於數據太過龐大,科學家終於忍受不了,想請聰明如你的ACMer來幫忙。
輸入
第一行輸入動物名字的數量N(1<= N <= 4000000),接下來的N行輸入N個字符串表示動物的名字(字符串的長度不超過10,字符串全爲小寫字母,並且只有一組測試數據)。 
輸出
輸出這些動物中最多的動物的名字與數量,並用空格隔開(數據保證最多的動物不會出現兩種以上)。 
樣例輸入
10
boar
pig
sheep
gazelle
sheep
sheep
alpaca
alpaca
marmot
mole
樣例輸出

sheep 3

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define N 26
char s[11];
int max;


typedef struct Trie
{  
    Trie *next[N];  //含有26個結點指針(a,b,c.......z)
    int count;
} *Node;


Node root;


Node creat()
{
    Node p = (struct Trie*) malloc(sizeof(struct Trie));
    for(int i = 0; i < N; ++i)
        p->next[i] = NULL;
    p->count = 0;
    return p;
}


void insertNode(char *str)
{
    Node p = root;
    int i, len = strlen(str);
    for(i = 0; i < len; ++i)
    {
        if(p->next[ str[i] - 'a' ] == NULL)
            p->next[ str[i] - 'a' ] = creat();
        p = p->next[ str[i] - 'a' ];
    }
    ++p->count;  //記錄該單詞出現的個數
    if(max < p->count)
    {
        max = p->count;
        strcpy(s,str);
    }
}


int main()
{
//    freopen("in.txt","r",stdin);
    int n;
    char a[11];
    root = creat();
    max = 0;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",a);
        insertNode(a);
    }
    printf("%s %d\n",s,max);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章