399. 查字典
☆ 输入文件:scanword.in
输出文件:
scanword.out
简单对比
时间限制:1 s 内存限制:128 MB
全国英语四级考试就这样如期来了,可是小 y 依然没有做好充分准备。为了能够大学毕业可怜的小 y 决定作弊。
小 y 费尽心机,在考试的时候夹带了一本字典进考场,但是现在的问题是,考试的时候可能有很多的单词要查,小 y 能不能来得及呢?
输入格式:
第一行一个整数 N ,表示字典中一共有多少个单词( N<=10000 )。
接下来每两行表示一个单词,其中:
第一行是一个长度 <=100 的字符串,表示这个单词,全部小写字母,单词不会重复。
第二行是一个整数,表示这个单词在字典中的页码。
接下来是一个整数 M ,表示要查的单词数 (M<=10000) 。
接下来 M 行,每行一个字符串,表示要查的单词,保证在字典中存在。
输出格式:
M 行,每行一个整数,表示第 I 个单词在字典中的页数。
输入样例:
2
scan
10
word
15
2
scan
word
输出样例
10
15
简单字典树。。
#include<cstdio>
#include<cstring>
using namespace std;
int id,tot;
char str[110];
struct node{
int f;
int next[26];
node () { memset(next,-1,sizeof(next)); f=-1;}
}T[10000*100];
void insert(){
int root=0;
for(int i=0;str[i];i++){
if(T[root].next[ str[i]-'a' ]==-1) T[root].next[ str[i]-'a' ]=tot++;
root=T[root].next[ str[i]-'a' ];
}
T[root].f=id;
}
int find(){
int root=0;
for(int i=0;str[i];i++){
root=T[root].next[ str[i]-'a' ];
}
return T[root].f;
}
int main(){
freopen("scanword.in","r",stdin);
freopen("scanword.out","w",stdout);
int n,m; tot=1;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%s %d",str,&id);
insert();
}
scanf("%d",&m);
while(m--){
scanf("%s",str);
printf("%d\n",find());
}
return 0;
}