/*
分析:
两个方法:
1、建立字典树:ans=2*节点数+n(因为要输出n次)-最长链长度。
用贪心的想法想局部,然后跳出来全局看,就得到这个结论了;
2、将所有的单词按字典序排序,然后遍历;
前者;62MS,29688K(中途释放的话会小很多很多),1091B
后者:31MS,736K,628B
下面是前者的代码。
2012-07-05
*/
分析:
两个方法:
1、建立字典树:ans=2*节点数+n(因为要输出n次)-最长链长度。
用贪心的想法想局部,然后跳出来全局看,就得到这个结论了;
2、将所有的单词按字典序排序,然后遍历;
前者;62MS,29688K(中途释放的话会小很多很多),1091B
后者:31MS,736K,628B
下面是前者的代码。
2012-07-05
*/
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
struct dic
{
struct dic *child[26];
};
struct dic *root;
int max;
int ans;
void insert(char *source)
{
struct dic *now,*newnode;
int i,j;
int len;
len=strlen(source);
max=max>len?max:len;
now=root;
for(i=0;i<len;i++)
{
if(now->child[source[i]-'a']!=NULL) now=now->child[source[i]-'a'];
else
{
newnode=(struct dic*)malloc(sizeof(struct dic));
for(j=0;j<26;j++) newnode->child[j]=NULL;
now->child[source[i]-'a']=newnode;
now=newnode;
}
}
}
void count(struct dic *now)
{
int j;
for(j=0;j<26;j++)
{
if(now->child[j]==NULL) continue;
else
{
ans++;
count(now->child[j]);
}
}
}
int main()
{
int n;
int i,j;
char str[55];
while(scanf("%d",&n)!=-1)
{
root=(struct dic *)malloc(sizeof(struct dic));
for(j=0;j<26;j++) root->child[j]=0;
max=0;
for(i=0;i<n;i++)
{
scanf("%s",str);
insert(str);
}
ans=0;
count(root);
ans*=2;
ans-=max;
ans+=n;
printf("%d\n",ans);
}
return 0;
}
本文探讨了字典树算法在解决单词计数问题上的应用,包括两种方法:一种是通过构建字典树来计算节点数并进行调整,另一种是先对所有单词进行排序再遍历。文中提供了字典树算法的实现代码,详细解释了两种方法的时间复杂度和空间复杂度,并对比了它们在实际运行中的表现。
9万+

被折叠的 条评论
为什么被折叠?



