单词查找树
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 16 Accepted Submission(s) : 8
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
在进行文法分析的时候,通常需要检测一个单词是否在我们的单词列表里。为了提高查找和定位的速度,通常都画出与单词列表所对应的单词查找树,其特点如下:
1.根结点不包含字母,除根结点外每一个结点都仅包含一个大写英文字母;
2.从根结点到某一结点,路径上经过的字母依次连起来所构成的字母序列,称为该结点对应的单词。单词列表中的每个单词,都是该单词查找树某个结点所对应的单词;
3.在满足上述条件下,该单词查找树的结点数最少。
1.根结点不包含字母,除根结点外每一个结点都仅包含一个大写英文字母;
2.从根结点到某一结点,路径上经过的字母依次连起来所构成的字母序列,称为该结点对应的单词。单词列表中的每个单词,都是该单词查找树某个结点所对应的单词;
3.在满足上述条件下,该单词查找树的结点数最少。
Input
输入有多组数据,对于每组数据第一行是n(n<10000),表示该组共有的单词数,下面n行每一行包含一个单词和一个换行/回车符。每个单词仅由大写的英文字母组成,长度不超过63个字母 。
Output
对于每组数据输出一个整数,该整数为单词列表对应的单词查找树的结点数。
Sample Input
8 A AN ASP AS ASC ASCII BAS BASIC
Sample Output
13 Hint 单词查找树包括根结点
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
int top;
char ch[70];
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));
top++;
NewNode->n = 1;
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++;
}
}
//ans->n=1;
}
int main ()
{
//freopen("a.txt","r",stdin);
int t,i;
while(cin>>t)
{Node *root=(Node*)malloc(sizeof(Node));
root->n=0;
for(i=0;i<26;i++) root->child[i]=NULL;
top=0;
for(i=0; i<t; i++)
{
cin>>ch;
Insert(root,ch);
}
printf("%d\n",++top);
}
return 0;
}
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
int top;
char ch[70];
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));
top++;
NewNode->n = 1;
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++;
}
}
//ans->n=1;
}
int main ()
{
//freopen("a.txt","r",stdin);
int t,i;
while(cin>>t)
{Node *root=(Node*)malloc(sizeof(Node));
root->n=0;
for(i=0;i<26;i++) root->child[i]=NULL;
top=0;
for(i=0; i<t; i++)
{
cin>>ch;
Insert(root,ch);
}
printf("%d\n",++top);
}
return 0;
}