2395 - 单词查找树
时间限制 : 1 秒
内存限制 : 128 MB
在进行文法分析的时候,通常需要检测一个单词是否在我们的单词列表里。为了提高查找和定位的速度,通常都画出与单词列表所对应的单词查找树,其特点如下:
1.根结点不包含字母,除根结点外每一个结点都仅包含一个大写英文字母;
2.从根结点到某一结点,路径上经过的字母依次连起来所构成的字母序列,称为该结点对应的单词。单词列表中的每个单词,都是该单词查找树某个结点所对应的单词;
3.在满足上述条件下,该单词查找树的结点数最少。
4.例如图左边的单词列表就对应于右边的单词查找树。注意,对一个确定的单词列表,请统计对应的单词查找树的结点数(包含根结点)。

题目输入
输入一个单词列表,每一行仅包含一个单词和一个换行/回车符。每个单词仅由大写的英文字母组成,长度不超过63个字母 。输入文件总长度不超过32K,至少有一行数据。
题目输出
输出一个整数,该整数为单词列表对应的单词查找树的结点数。
输入/输出样例
输入格式
A AN ASP AS ASC ASCII BAS BASIC
输出格式
13
C语言解答
#include <stdio.h> #include <stdlib.h> #include <string.h> #define maxn 100000 struct node{ int child[28]; int len; char value; }A[maxn]; int ans; void proc(int index, char s[], int n){ if(n>=strlen(s))return; int i; for(i = 0;i < A[index].len; i++){ if(A[A[index].child[i]].value == s[n])break; } if(i>=A[index].len){ A[++ans].value=s[n]; A[index].child[A[index].len++]=ans; } proc(A[index].child[i],s,n+1); } int main() { char s[70]; ans = 1; memset(A,0,sizeof(A)); while(scanf("%s",s) != EOF) { proc(1,s,0); } printf("%d\n",ans); return 0; }
C++解答
#include<cstdio> #include<cstring> #include<iostream> using namespace std; struct re{ bool got; int next[30]; } t[26000]; char s[100]; int now,size=0; int main(){ char ch; while (cin>>s){ now=0; for(int i=0;i<strlen(s);++i) if (t[now].next[s[i]-'A']!=0) now=t[now].next[s[i]-'A']; else { size++; t[size].got=false; memset(t[size].next,0,sizeof(t[size].next)); t[now].next[s[i]-'A']=size; now=size; } t[now].got=true; } printf("%d",size+1); return 0; }