单词查找树
2013-11-20 21:21
225 查看
Problem Description
在进行文法分析的时候,通常需要检测一个单词是否在我们的单词列表里。为了提高查找和定位的速度,通常都画出与单词列表所对应的单词查找树,其特点如下:1.根结点不包含字母,除根结点外每一个结点都仅包含一个大写英文字母;
2.从根结点到某一结点,路径上经过的字母依次连起来所构成的字母序列,称为该结点对应的单词。单词列表中的每个单词,都是该单词查找树某个结点所对应的单词;
3.在满足上述条件下,该单词查找树的结点数最少。
Input
输入有多组数据,对于每组数据第一行是n(n<10000),表示该组共有的单词数,下面n行每一行包含一个单词和一个换行/回车符。每个单词仅由大写的英文字母组成,长度不超过63个字母 。
Output
对于每组数据输出一个整数,该整数为单词列表对应的单词查找树的结点数。
Sample Input
8 A AN ASP AS ASC ASCII BAS BASIC
Sample Output
13
// 关键字: 简单字典树问题
//标程:
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
int cnt;
typedef struct Node
{
Node *child[26];
int n;
}Node;
void Insert(Node *root,char *str)
{
int len = strlen(str);
Node *ans = root;
for (int i=0;i<len; i++)
{
if (ans->child[str[i]-'A'] == NULL)
{
Node *NewNode = (Node*) malloc (sizeof (Node));
cnt++;
NewNode->n=0;
for (int j = 0;j<26;j++) NewNode->child[j]=NULL;
ans->child[str[i]-'A']=NewNode;
ans = NewNode;
}
else ans=ans->child[str[i]-'A'];
}
ans->n=1;
}
void release(Node* root)
{
int i;
for(i=0;i<26;i++) if(root->child[i]!=NULL) release(root->child[i]);
delete root;
}
char s[200];
int main()
{
//freopen("a.txt","r",stdin);
int i,t;
while(cin>>t)
{
Node *root=(Node*)malloc (sizeof (Node));
root->n =0;
for (i=0;i<26;i++) root->child[i]=NULL;
cnt=0;
for(i=0;i<t;i++)
{
cin>>s;
Insert(root,s);
}
printf("%d\n",++cnt);
release(root);
}
return 0;
}
相关文章推荐
- linux下tar命令实例
- Codeforces Round #213 (Div. 1)
- FZU 2020 组合 Lucas的应用
- WinForm各种关闭
- Servlet3.0引入的新特性
- linux segmentation fault记录
- 在ArcGIS中计算震中到周边城市的距离,并连线标注
- iOS7滑动返回
- perl学习过程
- openSUSE v13.1
- linux segmentation fault记录
- 最大价值
- SQLite
- 业务逻辑层的设计(五)——事务脚本模式介绍
- js显示时间
- Java Hour 46 SLF4J
- 注册——登录实战演习 (使用java web应用的三层架构实现)
- 从最大似然到EM算法浅解
- c++学习之--排序4-直接选择排序
- 【OpenCV】数字图像灰度直方图