字典树 HDU 1251 统计难题
2024-08-29 23:16:34
http://acm.hdu.edu.cn/showproblem.php?pid=1251 这是重写的,让我感觉到每一次的理解程度都在增加
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
using namespace std;
struct node
{
int sum;
node *next[];
node()//初始化数据
{
memset(next, NULL, sizeof(next));
sum=;
}
};
node *head=new node();//用C++的new动态申请内存其实delete和new是一对儿哦
node *now=(node *)malloc(sizeof(node));//用C语言动态申请内存
void buildtiretree(char *s)//建立字典数
{
node *p=new node();
p=head;
for(int i=; s[i]; i++)
{
int k=s[i]-'a';
if(p->next[k]==NULL)//如果p->next[k]为空
p->next[k]=new node();//就动态申请一个内存
now=p->next[k];
now->sum++;
p=now;
/*也可以这样写,其实就是第一个,也就是head不存任何东西
p=p->next[k];
p->sum++;
*/
}
}
int query(char *s)//查询单词
{
node *p=new node();
p=head;
//node *p=head;
for(int i=; s[i]; i++)
{
int k=s[i]-'a';
if(p->next[k]==NULL)
return;
p=p->next[k];
}
return p->sum;
}
void Free(node *head)//释放内存
{
int i;
if(head==NULL)
return;
for(i=; i<; i++)
{
if(head->next[i]!=NULL)
Free(head->next[i]);
}
free(head);
head=NULL;
}
int main()
{
char s[];
while(gets(s), s[])
buildtiretree(s);
while(cin >> s)
printf("%d\n", query(s));
Free(head);
return;
} 之前写的
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
struct node
{
int sum;
node *next[];
};
void buildtrietree(node *head, char s[])
{
node *p=new node();
p=head;
for(int i=; s[i]; i++)
{
int k=s[i]-'a';
if(p->next[k]==)
p->next[k]=new node();
p=p->next[k];
p->sum++;
}
} int query(node *head, char s[])
{
node *p=new node();
p=head;
for(int i=; s[i]; i++)
{
int k=s[i]-'a';
if(p->next[k]==)
return;
p=p->next[k];
}
return p->sum;
}
int main()
{
char s[];
node *head=new node();
while(gets(s), s[])
buildtrietree(head, s);
while(cin >> s)
printf("%d\n", query(head, s));
return;
}
最新文章
- XLT格式化XML那点事(C#代码中的问题解决)(二)
- (转)HTTP长连接和短连接
- Linux下C程序的编辑,编译和运行以及调试
- android6.0源码分析之Camera API2.0下的Capture流程分析
- Swift - 03 - 整数类型
- HDU 2639 Bone Collector II(01背包变型)
- 08-C语言循环
- liunx常用命令
- 测试工具——JMeter
- DBUtils源码分析
- Unity进阶----AssetBundle_02(加载依赖关系及网络资源)(2018/10/31)
- CDQ分治与整体二分学习笔记
- error C4996: &#39;sprintf&#39;: This function or variable may be unsafe.
- svn: 提交终止
- Lucene6.6.0 案例与学习路线
- 非[无]root权限 服务器 下安装perl以及perl模块
- 『Re』知识工程作业_主体识别
- mysql 按照 where in 排序
- koa中接收前台传递的各种数据类型的方式
- IDEA2018 license