湖南省第八届大学生程序设计大赛原题 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
Sample Output
分析:字典树的模板题
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; }
相关文章推荐
- 编写shell管理脚本(二)
- 新手,我在好奇,number1、number2的数字是怎么获取的
- 程序员常用的编辑器
- android动画之从源码角度分析动画原理(一)
- 强大的vim配置文件,让编程更随意
- UIButton
- A - 食物链
- IOS--UI--LessonThread 线程
- 黑马程序员--iOS基础知识---C语言中的函数
- secureCRT for mac破解
- 图解 Monad
- LayoutInflater.inflate详解
- 虚拟机中centos7实现nat静态ip上网
- Android studio在函数头部添加说明性注释和参数的注释的快捷键
- C++基于TCP/IP简单的客户端、服务器通信程序实例
- hdu1712ACboy needs your help 分组背包模板题
- 编写shell管理脚本(一)
- ubuntu14.04-安装flash
- Tarena - 职业发展规划之态度
- hdu 5325 Crazy Bobo 附上证明 Multi-University Training Contest 3