HDU 1251 統計難題 字典樹

統計難題

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 20031    Accepted Submission(s): 8776


Problem Description
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字符串爲前綴的單詞數量(單詞本身也是自己的前綴).
 

Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.

注意:本題只有一組測試數據,處理到文件結束.
 

Output
對於每個提問,給出以該字符串爲前綴的單詞的數量.
 

Sample Input
banana band bee absolute acm ba b band abc
 

Sample Output
2 3 1 0
 

Author
Ignatius.L


#include <stdio.h>
#include <string.h>

struct node
{
    int flag;
    node *next[26];
};

void build(node *&head,char str[],int len)
{
    node *p = head,*q;
    for(int i = 0;i < len;i++)
    {
        int zh = str[i] - 'a';
        if(!p->next[zh])
        {
            q = new node;
            memset(q->next,0,sizeof(q->next));
            q->flag = 1;
            p->next[zh] = q;
            p = q;
        }
        else
        {
            p = p->next[zh];
            p->flag++;
        }
    }
}

void nfind(node *&head,char str[],int len)
{
    node *p = head;
    for(int i = 0;i < len;i++)
    {
        int zh = str[i] - 'a';
        if(p->next[zh])
            p = p->next[zh];
        else
        {
            printf("0\n");
            return ;
        }
    }
    printf("%d\n",p->flag);
}

int main()
{
    char str[15];
    bool flag = false;
    node *head = new node;
    memset(head->next,0,sizeof(head->next));
    while(gets(str))
    {
        int len = strlen(str);
        if(!len)
        {
            flag = true;
            continue;
        }
        if(flag)
        {
            nfind(head,str,len);
        }
        else
        {
            build(head,str,len);
        }
    }
    return 0;
}





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