您的位置:首页 > 其它

湖南省第八届大学生程序设计大赛原题 E

2015-07-30 20:59 351 查看
E - 最短的名字
Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Submit Status Practice CSU 1115

Description

在一个奇怪的村子中,很多人的名字都很长,比如aaaaa, bbb and abababab。
名 字这么长,叫全名显然起来很不方便。所以村民之间一般只叫名字的前缀。比如叫'aaaaa'的时候可以只叫'aaa',因为没有第二个人名字的前三个字母 是'aaa'。不过你不能叫'a',因为有两个人的名字都以'a'开头。村里的人都很聪明,他们总是用最短的称呼叫人。输入保证村里不会有一个人的名字是 另外一个人名字的前缀(作为推论,任意两个人的名字都不会相同)。
如果村里的某个人要叫所有人的名字(包括他自己),他一共会说多少个字母?

Input

输入第一行为数据组数T (T<=10)。每组数据第一行为一个整数n(1<=n<=1000),即村里的人数。以下n行每行为一个人的名字(仅有小写字母组成)。输入保证一个村里所有人名字的长度之和不超过1,000,000。

Output

对于每组数据,输出所有人名字的字母总数。

Sample Input

1
3
aaaaa
bbb
abababab


Sample Output

5


分析:字典树的模板题

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
#define MAX 28
struct node{
int flag;//标记是否为节点
int num;;//表示一个字典树到此有多少相同前缀的数目
struct node *next[MAX];
};

void Insert(node *root,char *str){
if(root==NULL&&*str=='\0')
return ;
node *p=root;
int last;//记录上一次经过的节点的num
while(*str!='\0'){
if(p->next[*str-'a']==NULL){
node *temp=new node;
for(int i=0;i<MAX;i++)
temp->next[i]=NULL;
temp->flag=0;
temp->num=0;
p->next[*str-'a']=temp;
}
p=p->next[*str-'a'];
p->num+=1;
str++;
}
p->flag=1;
}

void Delete(node *root){
for(int i=0;i<MAX;i++)
if(root->next[i]!=NULL)
Delete(root->next[i]);
delete (root);
}

int Query(node *root,int cnt){
int sum=0;
if(root->num==1)
return cnt;
for(int i=0;i<MAX;i++)
if(root->next[i]!=NULL)
sum+=Query(root->next[i],cnt+1);
return sum;
}

int main(){
char str[1000005];
int T,n;
cin>>T;
while(T--){
node *root=new node;
for(int i=0;i<MAX;i++)
root->next[i]=NULL;
root->flag=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>str;
Insert(root,str);
}
cout<<Query(root,0)<<endl;
Delete(root);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: