統計的な課題(ディクショナリ・ツリー)

4538 ワード

統計的難題Time Limit:4000/2000 MS(Java/others)Memory Limit:131070/65535 K(Java/others)Total Submission(s):45073 Accepted Submission(s):16110
Problem Description Ignatiusは最近、ある文字列を接頭辞とする単語の数(単語自体も自分の接頭辞)を統計するように先生に頼まれた難題に直面した.
Input入力データの第1部は1枚の単語表で、各行に1つの単語、単語の長さは10を超えないで、それらは先生がIgnatius統計の単語に渡したことを代表して、1つの空行は単語表の終わりを代表します.第2部は一連の質問で、各行に1つの質問で、各質問はすべて1つの文字列です.
注意:本題はテストデータのセットだけで、ファイルが終わるまで処理します.
Outputは質問ごとに、その文字列を接頭辞とする単語の数を与える.
Sample Input
banana band bee absolute acm
ba b band abc
Sample Output
2 3 1 0この问题のコンパイラはC++で提出しなければタイムアウトです!!!
#include
#include
#include
#include
#include

using namespace std;

struct node
{
    int v;
    struct node *next[26];//     
}*root;
void Insert(string str)
{
    int cnt =0;
    node *p = root;
    while(str[cnt])
    {
        int indx = str[cnt] - 'a';
        if(p->next[indx]==NULL)
        {
            node *q = (node *)malloc(sizeof(struct node));
            for(int i =0;i<26;i++)
            {
                q->next[i] = NULL;
            }
            q->v = 0 ;
            p->next[indx] = q;
        }
        p = p->next[indx];
        p->v++;//                1
        cnt++;
    }
}
//                      
void deletenode(node *p)
{
    for(int i =0;i<26;i++)
    {
        if(p->next[i])
            deletenode(p->next[i]);
    }
    free(p);
}
int findpattern(string str)
{
    int cnt =0;
    node *p = root;
    while(str[cnt])
    {
        int indx = str[cnt] -'a';
        if(p->next[indx]==NULL)
            return 0;
        p = p->next[indx];
        cnt++;
    }
    return p->v;
}
int main()
{
    string str;
    root = (node *)malloc(sizeof(struct node));
    for(int i =0;i<26;i++)
        root->next[i] = NULL;
    root->v = 0;
    while(getline(cin,str)&&str[0])
    {
        Insert(str);
    }
    while(getline(cin,str))
    {
        int ans = findpattern(str);
        printf("%d
"
,ans); } deletenode(root); return 0; }