一道字典树的模板题。中文题就不讲题意了。值得注意的是题目中是以空行来分隔输入与询问的,这对于稍微熟悉字符串输入函数的人来说应该不会太难。
第一份代码没写删除内存的函数、、、现在在第二份代码中补上,良好的编程习惯还是要有的,呵呵、、、
下面是我的解题代码:动态字典树解题
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define N 11
struct dt //构造字典树结构体
{
dt *chid[26];
int num; //代表前缀为此单词的个数,当然如果是根节点的话代表的就是所有单词的个数了
dt() //初始化
{
num = 0;
memset(chid, 0, sizeof(chid));
}
};
dt *root; //根节点
char str[N]; //待输入的字符串
int strn; //字符串长度
int GetID(char ch); //获得字母的id
void Read(); //输入单词
void Query(); //询问str符串为前缀的单词个数
int main()
{
root = new dt;
while (true)
{
gets(str);
if ((strn = strlen(str)) == 0) break; //空行时跳出
Read();
}
while (~scanf("%s", str))
{
strn = strlen(str);
Query();
}
return 0;
}
int GetID(char ch)
{
return ch - 'a';
}
void Read()
{
dt *next = root;
int strn = strlen(str);
int chnum;
for (int i=0; i<strn; ++i)
{
chnum = GetID(str[i]);
if (next->chid[chnum] == NULL)
{
next->chid[chnum] = new dt;
}
next->num += 1;
next = next->chid[chnum];
}
next->num++;
return;
}
void Query()
{
dt *next = root;
int chnum;
for (int i=0; i<strn; ++i)
{
chnum = GetID(str[i]);
if (next->chid[chnum] == NULL)
{
puts("0");
return;
}
next = next->chid[chnum];
}
printf("%d\n", next->num);
return;
}
现在在这里补上有些删除内存函数的代码:
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define N 11
struct dt //构造字典树结构体
{
dt *chid[26];
int num; //代表前缀为此单词的个数,当然如果是根节点的话代表的就是所有单词的个数了
dt() //初始化
{
num = 0;
memset(chid, 0, sizeof(chid));
}
};
dt *root; //根节点
char str[N]; //待输入的字符串
int strn; //字符串长度
int GetID(char ch); //获得字母的id
void Read(); //输入单词
void Query(); //询问str符串为前缀的单词个数
void Delete(dt *p); //递归删除字典树
int main()
{
root = new dt;
while (true)
{
gets(str);
if ((strn = strlen(str)) == 0) break; //空行时跳出
Read();
}
while (~scanf("%s", str))
{
strn = strlen(str);
Query();
}
Delete(root);
return 0;
}
int GetID(char ch)
{
return ch - 'a';
}
void Read()
{
dt *next = root;
int strn = strlen(str);
int chnum;
for (int i=0; i<strn; ++i)
{
chnum = GetID(str[i]);
if (next->chid[chnum] == NULL)
{
next->chid[chnum] = new dt;
}
next->num += 1;
next = next->chid[chnum];
}
next->num++;
return;
}
void Query()
{
dt *next = root;
int chnum;
for (int i=0; i<strn; ++i)
{
chnum = GetID(str[i]);
if (next->chid[chnum] == NULL)
{
puts("0");
return;
}
next = next->chid[chnum];
}
printf("%d\n", next->num);
return;
}
void Delete(dt *p)
{
int i;
for (i=0; i<26; ++i)
{
if (p->chid[i] != NULL)
{
Delete(p->chid[i]);
}
}
delete p;
return;
}