您的位置:首页 > 其它

单词查找树

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: