字典树 HDU 1251 统计难题
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[26];
node()//初始化数据
{
memset(next, NULL, sizeof(next));
sum=0;
}
};
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=0; 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=0; s[i]; i++)
{
int k=s[i]-'a';
if(p->next[k]==NULL)
return 0;
p=p->next[k];
}
return p->sum;
}
void Free(node *head)//释放内存
{
int i;
if(head==NULL)
return;
for(i=0; i<26; i++)
{
if(head->next[i]!=NULL)
Free(head->next[i]);
}
free(head);
head=NULL;
}
int main()
{
char s[15];
while(gets(s), s[0])
buildtiretree(s);
while(cin >> s)
printf("%d\n", query(s));
Free(head);
return 0;
}
之前写的
#include<iostream> #include<algorithm> #include<stdio.h> using namespace std; struct node { int sum; node *next[26]; }; void buildtrietree(node *head, char s[]) { node *p=new node(); p=head; for(int i=0; s[i]; i++) { int k=s[i]-'a'; if(p->next[k]==0) 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=0; s[i]; i++) { int k=s[i]-'a'; if(p->next[k]==0) return 0; p=p->next[k]; } return p->sum; } int main() { char s[12]; node *head=new node(); while(gets(s), s[0]) buildtrietree(head, s); while(cin >> s) printf("%d\n", query(head, s)); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步