思路:

  完全看题目中的介绍就行了。还有里面的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代码

最新文章

  1. MySQL性能优化总结(转)https://yq.aliyun.com/articles/24249
  2. node中使用domain处理异步异常问题
  3. Python之路Day8
  4. 最小生成树算法prim and kruskal
  5. GitBash学习1
  6. B树、B+树、B*树
  7. [HNOI 2014]米特运输
  8. vb越界
  9. Codeforces Round #308 (Div. 2)
  10. KMSpico 无后门下载
  11. 解决从本地文件系统上传到HDFS时的权限问题
  12. 使用SpringBoot Admin监控SpringCloud微服务
  13. Zabbix配置优化
  14. iOS开发--UILabel可以显示\n
  15. jrebel使用
  16. sp_trace_setevent sqlserver跟踪事件及列
  17. nginx 413 request entity too large解决办法
  18. 《DSP using MATLAB》示例Example6.2
  19. tcl之变量-数组array
  20. python - 接口自动化测试 - TestLogin - 登录接口测试用例

热门文章

  1. 该项目中不存在目标“GatherAllFilesToPublish”
  2. EasyOffice-.NetCore一行代码导入导出Excel,生成Word
  3. Flask从入门到做出一个博客的大型教程(一)
  4. [WIP]laravel 构成的概念
  5. 51nod 1405【DFS】
  6. windows severs 2008r2 180天激活
  7. msyql分区与分库分表
  8. mysql 日期与索引问题
  9. svn更改账户信息
  10. c/c++ socket发送http请求访问网站