Hdu oj 1251統計難題(辞書ツリー)
統計上の課題
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others) Total Submission(s): 29559 Accepted Submission(s): 11572
Problem Description
Ignatiusは最近、ある文字列を接頭辞とする単語の数(単語自体も自分の接頭辞)を統計するように要求された.
Input
入力データの第1部は1枚の単語表で、1行ごとに1つの単語、単語の長さは10を超えないで、それらは先生がIgnatiusに渡して統計した単語を代表して、1つの空行は単語表の終わりを代表します.第2部は一連の質問で、各行は1つの質問で、各質問はすべて1つの文字列です.
注意:本題はテストデータのセットだけで、ファイルが終わるまで処理します.
Output
各質問に対して、その文字列を接頭辞とする単語の数を与える.
Sample Input
Sample Output
Author
Ignatius.L
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1075 1247 1671 1298 2846
文字列の接頭辞と問題がはっきりしているので、辞書の木のテンプレートを変えればいいです.
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others) Total Submission(s): 29559 Accepted Submission(s): 11572
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
Recommend
Ignatius.L | We have carefully selected several similar problems for you: 1075 1247 1671 1298 2846
文字列の接頭辞と問題がはっきりしているので、辞書の木のテンプレートを変えればいいです.
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char str[11];
struct node{
node *next[26];
int cnt;//
node(){// ,
cnt=0;
for(int i=0;i<26;i++)
next[i]=NULL;// 26
}
};
void insert(node *p,char *str){
for(int i=0;str[i];i++){
int t=str[i]-'a';
if(p->next[t]==NULL)
p->next[t]=new node;// , new
p=p->next[t];//
p->cnt++;//
}
}
int find(node *p,char *str){
for(int i=0;str[i];i++){
int t=str[i]-'a';
p=p->next[t];//
if(!p)//p
return 0;
}
return p->cnt;
}
int main(){
node *root=new node();
while(gets(str)&&strlen(str))
insert(root,str);
while(gets(str)){
int ans=find(root,str);
printf("%d
",ans);
}
return 0;
}