题意:先输入单词再输入前缀,统计有相同前缀的单词有多少个。
坑点:一定要用c++交,用g++就MLE;
以前写的字典树从来没有delet这个环节,后来发现自己真是太戳了,借了人家的内存居然不还,补充一下delet模板
void del(struct Node *proot)
{
for(int i=0;i<26;i++)
if(proot->next[i]!=NULL)
del(proot->next[i]);
delete(proot);//不要搞混了,这个delete是删除函数
}
好了,贴一份目前我认为是我标准字典树的模板:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <algorithm>
using namespace std;
struct Node
{
struct Node *next[26];
int cnt;
Node()
{
cnt=0;
for(int i=0;i<26;i++)
next[i]=NULL;
}
};
struct Node *root = new struct Node;
void inset(char *str)
{
struct Node *cur = root;
for(int i=0;str[i];i++)
{
if(cur->next[str[i]-'a']==NULL)
{
struct Node *newnode = new struct Node;
cur->next[str[i]-'a'] = newnode;
}
cur = cur->next[str[i]-'a'];
cur->cnt ++;
}
return;
}
int query(char *str)
{
struct Node *cur = root;
for(int i=0;str[i];i++)
{
if(cur->next[str[i]-'a']!=NULL)
{
cur= cur->next[str[i]-'a'];
}
else return 0;
}
return cur->cnt;
}
void Delet(struct Node *proot)
{
for(int i=0;i<26;i++)
if(proot->next[i]!=NULL)
Delet(proot->next[i]);
delete proot;
}
int main()
{
char str[20];
while(gets(str) && str[0]!='\0')
{
inset(str);
}
while(gets(str))
{
printf("%d\n",query(str));
}
Delet(root);
return 0;
}