思路:
完全看题目中的介绍就行了。还有里面的input写道:不保证是英文单词,也有可能是火星文单词哦。比赛结束后的提交是不用考虑26个字母之外的,都会AC,如果考虑128种可能的话,爆了内存。步骤就是,在插单词的同时记录该结点之后的单词数,查词就查最后一个字母所在结点上的单词数。
#include <iostream>
#include <cstring>
#include <vector>
#include <stdio.h>
using namespace std;
const int N=;
char dict[];
int n, m;
struct node
{
int num; //以本节点开头的单词个数
node *child[N]; //孩子
}tree_gen; int check_dict(char *p)
{
node *node_p=&tree_gen; //指向树根
int ans=;
while(*p!='\0')
{
if(node_p->child[*p-'a']!=)
{
node_p=node_p->child[*p-'a'];
ans=node_p->num;
}
else
return ;
p++;
}
return ans;
} int insert_tree(char *p)
{
node *node_p=&tree_gen; //指向树根
node_p->num++; //访问这个节点
while(*p!='\0')
{
if( node_p->child[*p-'a']== ) //还没有这叉,就要建
{
node *new_node=new(node); //创建新节点
for(int i=; i<N; i++)
new_node->child[i]=;
new_node->num=;
node_p->child[*p-'a']=new_node; //连接工作
node_p=new_node;
}
else //已有这叉,继续往下
node_p=node_p->child[*p-'a'];
node_p->num++; //访问这个节点
p++;
}
return ;
} int main()
{
//freopen("e:input.txt", "r", stdin);
tree_gen.num=; //树根的初始化
for(int i=; i<N; i++) tree_gen.child[i]=; cin>>n;getchar();
for(int i=; i<n; i++) //接受字典,顺便插入,顺便记录num
{
gets(dict);
insert_tree(dict);
}
cin>>m;getchar();
for(int i=; i<m; i++) //查询以xxx开头的单词个数
{
gets(dict);
cout<<check_dict(dict)<<endl;
}
return ;
}
AC代码
还有一种不是以链表实现的树,而是用数组来做的。小Ho做的这代码可以过一些小一点的数据。
#include <cstdio>
#include <cstring> const int MAXL = + ;
const int MAXN = + ;
const int MAXM = + ; int next[MAXN * MAXL][], count[MAXN * MAXL]; int main() {
int n;
while (scanf("%d", &n) != EOF) {
int top = ; memset(next, , sizeof(next));
char str[MAXL];
for (int i = ; i < n; i++) {
scanf("%s", str);
int p = ;
for (int j = ; str[j] != '\0'; j ++) {
if (next[p][str[j] - 'a'] == ) next[p][str[j] - 'a'] = ++top;
p = next[p][str[j] - 'a'];
count[p] ++;
}
}
int m;
scanf("%d", &m);
while (m --) {
scanf("%s", str);
int p = ;
for (int j = ; str[j] != '\0'; j++) {
p = next[p][str[j] - 'a'];
}
printf("%d\n", count[p]);
}
}
}
Not AC代码