文字列4統計の難題

3139 ワード

統計上の課題
Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131070/65535K (Java/Other)
Total Submission(s) : 4   Accepted Submission(s) : 2
Problem Description
Ignatiusは最近、ある文字列を接頭辞とする単語の数(単語自体も自分の接頭辞)を統計するように要求された.
 
Input
入力データの第1部は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

 
Author
Ignatius.L
 
題意:辞書表、すなわちいくつかの文字列を与えます.それから文字列をいくつか与えて、辞書の表の中にこの冒頭の単語が何個あるかを聞きます.
考え方:辞書ツリー.木を建てる過程は26文字で子供を作り,nはこの列を通過した個数を記録する.
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;
struct dictree
{
    struct dictree *child[27];
    int n;
};
struct dictree *root;
void insert(char *str)
{
    int len;
    len=strlen(str);
    struct dictree *current,*newnode;
    if(len==0) return;
    current=root;
    for(int i=0;i<len;i++)
    {
        if(current->child[str[i]-'a']!=0)
        {
            current=current->child[str[i]-'a'];
            current->n=current->n+1;
        }
        else
        {
            newnode=(struct dictree *)malloc(sizeof(struct dictree));
            for(int j=0;j<26;j++)
            newnode->child[j]=0;
            current->child[str[i]-'a']=newnode;
            current=newnode;
            current->n=1;
        }
    }
}
int find(char *str)
{
    int len;
    struct dictree *current;
    len=strlen(str);
    current=root;
    for(int i=0;i<len;i++)
    {
        if(current->child[str[i]-'a']!=0)
        current=current->child[str[i]-'a'];
        else
        return 0;
    }
    return current->n;
}
int main()
{
    char str[11];
    root=(struct dictree *)malloc(sizeof(struct dictree));
    for(int i=0;i<26;i++)
    root->child[i]=0;
    root->n=2;
    while(gets(str))
    {
        if(strcmp(str,"")==0)break;
        insert(str);
    }
    while(scanf("%s",str)!=EOF)
    {
        printf("%d
",find(str)); } return 0; } /* banana band bee absolute acm ba b band abc */